Skip to content

Instantly share code, notes, and snippets.

@yashsway
Last active February 15, 2023 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yashsway/8462443baccb3474af157518f06cb5e2 to your computer and use it in GitHub Desktop.
Save yashsway/8462443baccb3474af157518f06cb5e2 to your computer and use it in GitHub Desktop.
Clamping a value between a given min and max i.e. never more than the max and never less than min
const clamp = (val, min = 0, max = 1) => {
// if provided min is somehow greater than max, exchange the values
if (min > max) {
[min, max] = [max, min];
}
// get the maximum of two minimized values
return Math.max(min, Math.min(max, val));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment