Skip to curriculum
Jump to the editor

1.6. Clamp, in-range and mean

Easy
Topics
10–20 min

Interfaces are full of number rules: a volume slider stays between 0 and 100, a carousel index wraps inside the number of slides, a rating badge shows the average score. Three small helpers cover most of them, and each has an edge that is easy to miss: bounds given in the wrong order, NaN from a bad input, an empty list.

Write three functions in math.js: clamp, inRange and mean.

Signature

JAVASCRIPT
function clamp(number, lower, upper) // a number between lower and upper
function inRange(number, start, end) // boolean
function mean(numbers)               // a number

Requirements

  1. clamp returns number when it is between lower and upper (both included), lower when it is below, and upper when it is above. It works when lower equals upper and with infinite bounds.
  2. clamp throws a RangeError when lower is greater than upper. This check comes first: clamp(NaN, 2, 1) throws too.
  3. Otherwise, clamp returns NaN when any argument is NaN. A NaN bound never counts as greater than the other bound, so it gives NaN, not an error.
  4. inRange is true when number is at least start and less than end: start is included, end is not.
  5. With two arguments, inRange(number, end) uses the range from 0 to end.
  6. When start is greater than end (also after rule 5), inRange swaps them first.
  7. inRange is false for an empty range and for NaN.
  8. mean returns the sum of the numbers divided by their count, without rounding, and NaN for an empty array. It does not change the array.

Examples

JAVASCRIPT
clamp(15, 0, 10);   // 10
clamp(-3, 0, 10);   // 0
clamp(5, 10, 0);    // throws RangeError
clamp(NaN, 0, 10);  // NaN
JAVASCRIPT
inRange(3, 2, 4);   // true
inRange(4, 2, 4);   // false: end is excluded
inRange(4, 8);      // true: 0 to 8
inRange(-3, -2, -6); // true: swapped to -6 to -2
JAVASCRIPT
mean([4, 2, 8, 6]); // 5
mean([]);           // NaN

Environment

  • Plain JavaScript in a browser page; the tests call the three globals from math.js.
  • Arguments are numbers (or NaN); strings and other types are not part of the tests.
  • Any built-in may be used.

Hints

  1. Which of Math.min and Math.max keeps a number from going below a bound?
  2. What does any comparison with NaN return?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…