Constraining a numeric value to a range
December 9th, 2009Okay, so this doesn’t strictly have anything to do with any JavaScript library, but it’s a handy little snippet of code to keep in your arsenal.
val = Math.max(cMin, Math.min(val, cMax));
In one line of code, we’ve automatically constrained val between cMin and cMax. Note that if cMax and cMin are reversed (cMax is less than cMin) val will immediately be set to cMin (the higher of the values).
We can, of course, rectify this when cMin and cMax are assigned values by calling
cMin = Math.min(cMin, cMax); cMax = Math.max(cmin, cMax);


Previous Post
Next Post

Leave a Reply