Clamping values in an array

To make sure all numbers in an array are within a given range, we can “clamp” them. Values below the minimum become min, values above the maximum become max.

// takes a minimum and maximum value, returns a function that clamps a value
const clamp = (min, max) => value => Math.max(Math.min(value, max), min)

// we can call this function on individual values
clamp(2, 3)(1)  // ⇒ 2 (because 1 is smaller than the minimum value of 2)
clamp(2, 3)(2)  // ⇒ 2
clamp(2, 3)(3)  // ⇒ 3
clamp(2, 3)(4)  // ⇒ 3 (because 4 is greater than the maximum value of 3)

// because the function is curried, we can pass it to .map() like this
[1, 16, 9, 0, -2, 8, 14].map(clamp(0, 10))  // ⇒ [1, 10, 9, 0, 0, 8, 10]

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.