Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

ewjoachim commented Apr 16, 2015

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

@aleroy

This comment has been minimized.

Copy link

aleroy commented May 8, 2015

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

@danschumann

This comment has been minimized.

Copy link

danschumann commented Jun 6, 2016

webgl has this also

@ecolban

This comment has been minimized.

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

This comment has been minimized.

Copy link

cannon commented Oct 3, 2016

Why did you post this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.