Thursday, August 05, 2021

Ruby times and and upto in Javascript

 Number.prototype.upto = function(t, cb) {

  var i = this;


  if(t < this) return +this;


  while (i <= t) {

    cb(i++);

  }


  return +this;

};


(1).upto(5, function(i){console.log(i);})



// Ruby = 5.times { |i| puts i }

// JS   = (1).times(function(i){console.log(i);})

Number.prototype.times = function(cb) {

  var i = -1;


  while (++i < this) {

    cb(i);

  }


  return +this;

}



(5).times(function(i){console.log(i);})