Useful JavaScript Game Extensions: Clamp

Give him the clamps!

Part 1 of my new 256 part series on simple JavaScript extensions to make game programming easy and fun!

 * Returns a number whose value is limited to the given range.
 * Example: limit the output of this computation to between 0 and 255
 * (x * 255).clamp(0, 255)
 * @param {Number} min The lower boundary of the output range
 * @param {Number} max The upper boundary of the output range
 * @returns A number in the range [min, max]
 * @type Number
Number.prototype.clamp = function(min, max) {
  return Math.min(Math.max(this, min), max);

Note that this extends the behavior of the Number class. Some may consider it poor form to “mess with” the JS built-ins, but I consider it poor form to expose a worse than necessary interface to the programmer. Compare:

// Namespace?
STRd6.Util.clamp(x * 255, 0, 255);
// global function clamp?
clamp(x * 255, 0, 255);
// Clean, simple and object oriented!
(x * 255).clamp(0, 255);

Stay tuned for the next 255 parts of the series!

One thought on “Useful JavaScript Game Extensions: Clamp

  1. Pingback: Useful JavaScript Game Extensions: Number#round

Leave a Reply

Your email address will not be published. Required fields are marked *