Number.prototype.gate()

a handy function to keep a number inside a range

by sperske

JavaScript

Number.prototype.gate = function(min, max) {
  return Math.min(Math.max(min, this), max);
}

let test = 10;

console.log(`gate inside 1-20: ${test} into ${test.gate(1, 20)}`);
console.log(`gate under 11-20: ${test} into ${test.gate(11, 20)}`);
console.log(`gate over 1-5: ${test} into ${test.gate(1, 5)}`);