Skip to content

Instantly share code, notes, and snippets.

@furf
Last active March 31, 2016 16:48
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 furf/3804250528b40b24121e2d081f627568 to your computer and use it in GitHub Desktop.
Save furf/3804250528b40b24121e2d081f627568 to your computer and use it in GitHub Desktop.
a more sophisticated clamp
/**
* Restrict a value to within specified boundaries.
* - If only the `value` is specified, the boundaries are 0 and 1.
* - If only the `value` and boundary `a` are specified, the boundaries
* are 0 and `a`.
* - If the value and both boundaries `a` and `b` are specified, the
* boundaries are `a` and `b`.
* Clamp does not enforce the proper ordering of the boundaries.
* Therefore, clamp(2, 1, 3) and clamp(2, 3, 1) will return the same
* result.
*
* @param {Number} value Numeric value to clamp between boundaries
* @param {Number} (optional) a "Lower" boundary or 1 in undefined
* @param {Number} (optional) b "Upper" boundary or 0 if undefined
* @returns {Number} value between boundaries `a` and `b` inclusive
*/
function clamp(value, a, b) {
var max, min;
if (arguments.length < 3) {
b = 0;
if (arguments.length < 2) {
a = 1;
}
}
max = Math.max(a, b);
min = Math.min(a, b);
return (value < min) ? min : (value > max) ? max : value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment