Clamping values in an array

Posted on August 12, 2020

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.

This can be useful when working with data coming from home automation sensors. By clamping what they return, unrealistic spikes in temperature could be moved into a realistic range.

// 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]
// 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]

Continue reading

July 24, 2020JavaScript

Shuffling arrays

With the Fisher-Yates algorithm, we can shuffle an array with true randomness. The likelihood of two shuffles giving the same result is minimal.

Read full article

Read all snippets →