Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created February 5, 2012 22:45
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save FGRibreau/1748259 to your computer and use it in GitHub Desktop.
Save FGRibreau/1748259 to your computer and use it in GitHub Desktop.
Ruby .times & .upto & .downto methods in JavaScript
// 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;
}
// Ruby = 1.upto(5) { |i| puts i }
// JS = (1).upto(5, function(i){console.log(i);})
Number.prototype.upto = function(t, cb) {
var i = this;
if(t < this) return +this;
while (i <= t) {
cb(i++);
}
return +this;
};
// Ruby = 15.downto(10) { |i| puts i }
// JS = (15).downto(10, function(i){console.log(i);})
Number.prototype.downto = function(t, cb) {
var i = this;
if(t > this) return +this;
while (i >= t) {
cb(i--);
}
return +this;
};
@christophemarois
Copy link

Very nice!

@MaxPleaner
Copy link

@maxigimenez
Copy link

Awesome! I started this project https://github.com/maxigimenez/extend-js-classes to collect this cain of things 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment