By clamp, we are referring to a way to restrict the value of a JavaScript number between two other numbers.
Basically, we cap a number val to the bounds of the segment [min, max].
For example:
clamp(10, 50 /* min */, 100 /* max */) // returns 50
clamp(20, 1 /* min */, 15 /* max */) // returns 15
clamp(8, 4 /* min */, 12 /* max */) // returns 8
This means that when clamped, a number will:
- keep its own value if it fits in the range imposed by
minandmax - take the value
minif it is lower than it - or take the
maxvalue if is higher than it.
To implement a number clamping function in JavaScript we can mix the Math.min() and Math.max() functions:
/**
* Returns a number whose value is limited to the given range.
*
* @param {Number} val The initial value
* @param {Number} min The lower boundary
* @param {Number} max The upper boundary
* @returns {Number} A number in the range (min, max)
*/
const clamp = (val, min, max) => Math.min(Math.max(val, min), max)
clamp(-10, 20, 30) // returns 20
clamp(25, 20, 30) // returns 25
clamp(500, 20, 30) // returns 30

If needed, one nice addition we can make to this function is to provide some default values for the min and max parameters:
const clamp = (val, min=1, max=10) => Math.min(Math.max(val, min), max)
clamp(5) // returns 5
clamp(-3) // returns 1
You can check out the full code my Github repository and see the live example here.
As a side note, we also have a clamp() function directly build into CSS.
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js
š Build a full trivia game app with LangChain
Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js