Skip to content

Instantly share code, notes, and snippets.

@kujon
Created May 24, 2012 13:13
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kujon/2781489 to your computer and use it in GitHub Desktop.
Save kujon/2781489 to your computer and use it in GitHub Desktop.
JavaScript: Clamp a number.
/**
* Clamps a number. Based on Zevan's idea: http://actionsnippet.com/?p=475
* params: val, min, max
* Author: Jakub Korzeniowski
* Agency: Softhis
* http://www.softhis.com
*/
(function(){Math.clamp=function(a,b,c){return Math.max(b,Math.min(c,a));}})();
@ewjoachim
Copy link

You're missing a semicolon between the 2 }} at the end

@aleroy
Copy link

aleroy commented May 8, 2015

Haha ... yes, we must appease the almighty Linters.

@danschumann
Copy link

webgl has this also

@ecolban
Copy link

ecolban commented Aug 14, 2016

Make the code more readable by placing the clamped value between the min and the max values, like this:

Math.min(Math.max(min, val), max)

@cannon
Copy link

cannon commented Oct 3, 2016

Why did you post this?

@lloydjatkinson
Copy link

^ What a stupid question.

@IceHacks
Copy link

^ agreed he must have brain cancer or he has tusugma

@milahu
Copy link

milahu commented Mar 2, 2021

there is missing at least 20 lines of license text : D Math.clamp = (n,a,z) => Math.max(a,Math.min(z,n));. naz!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment