void setup(){ unittestLimit(); } /** * Limits a value to a given range * @param minValue the smallest allowed value (inclusive) * @param value the value * @param maxValue the largest allowed value (incluseive) * @return the value, if it is inside the range, else the closest allowed value * @throws IllegalArgumentException if minValue is larger than maxValue */ int limit(int minValue, int value, int maxValue){ if (minValue > maxValue){ throw new IllegalArgumentException("invalid range [" + minValue + ", " + maxValue + "]"); } return max(minValue, min(value, maxValue)); } void unittestLimit(){ assertEqual(100, limit(0, 100, 200), "in range"); assertEqual(0, limit(0, -300, 200), "negative. lower"); assertEqual(200, limit(0, 300, 200), "higher"); assertEqual(0, limit(0, 0, 0), "all identical values"); assertEqual(0, limit(0, 0, 10), "on lower limit"); assertEqual(100, limit(0, 100, 100), "on upper limit"); } /* crude unit test method. * Prints an error message if the actual value is different from the expected, else does nothing. * @param expected the value you expect * @param actual the actual value * @param message A message that helps you identify what went wrong (printed on failure) */ void assertEqual(int expected, int actual, String message){ if (actual != expected){ System.err.println("Assertion failed (" + message+ "): expected " + expected + ", got " + actual); } }