Skip to content

Instantly share code, notes, and snippets.

@subzey
Created September 13, 2016 13:53
Show Gist options
  • Select an option

  • Save subzey/f5d9f240e8d27eeebf5c56d02a3b4743 to your computer and use it in GitHub Desktop.

Select an option

Save subzey/f5d9f240e8d27eeebf5c56d02a3b4743 to your computer and use it in GitHub Desktop.
clamp.js
function clamp(min, max, mid){
if (min <= max) { // Sanity check
if (mid > max) {
// Also implied: mid is not NaN
return max;
}
if (mid < min) {
// Also implied: mid is not NaN
return min;
}
// At this point mid is either between min and max or it's NaN.
// Both cases are okay, we just return what we have.
return mid;
} else {
// Oops! max is less than min.
// Or worse: min or max (or both) is NaN
return NaN;
}
}
// Does this func look too verbose?
// We'll anyway pass it through the minifier in the production build.
// And afther the uglifyjs we'll get this:
// function clamp(n,a,c){return a>=n?c>a?a:n>c?n:c:NaN}
// Minifiers are pretty smart nowadays!
// You may wonder why I've change the signature
// from (min, mid, max)
// to (min, max, mid).
// That may look like a strange decision, but look what we can do now.
// Partial applications!
var zeroToOneClamp = clamp.bind(null, 0, 1);
zeroToOneClamp(42); // 1
zeroToOneClamp(0.5); // 0.5
zeroToOneClamp(-42); // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment