# 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]``````

June 19, 2020JavaScript

## Hiding repetition with helper functions

We can hide the repetition in a function’s parameters in a higher-order function.

July 20, 2020JavaScript

## Filtering falsy values from arrays

To filter all falsy values from arrays, all we need to do is pass the Boolean constructor to the filter function.

June 26, 2020JavaScript

## Switching between functions with a ternary operator

The ternary operator isn’t limited to assigning values based on a condition. It also lets us switch between two near identical function calls.

January 4, 2021JavaScript

## Getting the largest number from an array

To find the largest value in an array of numbers, we can spread that array into Math.max() instead of manually iterating over it.

August 15, 2020General

## Extracting complex logic to named functions

Putting complex logic into a function increases code readability. By giving that function a descriptive name, it can explain what is happening in it.