Receives an (ordered) array of numbers, denoting ranges, returns the first range it falls between - Node.js Number

Node.js examples for Number:Algorithm

Description

Receives an (ordered) array of numbers, denoting ranges, returns the first range it falls between

Demo Code


// 4..fallsAfter( [1, 2, 5] )  === 2
// 4..fallsAfter( [0, 3] ) === 3
Number.prototype.fallsAfter = function ( ranges ) {
  ranges = ranges.slice();//from  w  w w  . j  a  va2  s. c om
  var min = ranges.shift(), max,
    n = this.valueOf();

  for ( var i = 0, l = ranges.length; i < l; i++ ) {
    max = ranges[ i ];

    if ( n < max ) {
      break;
    }
    min = max;
  }

  return min <= n ? min : null;
};

Related Tutorials