DEV Community

Nick Ciolpan for Graffino

Posted on

Ruby's .times in JavaScript

Never modify JavaScript's standard built-in objects. That's what they say.

But just for fun, let's see how Ruby's .times would look like in JavaScript.

Here's how we do it:

String.prototype.times = function (n) {
    for (var i = 0; i < parseInt(this); i++) {
        n();
    }
}
var myFunc = function () { console.log('Hello World') }
"2".times(myFunc)

Output:

"Hello World"
"Hello World"

nickciolpan
29 May 2018

Top comments (0)