DEV Community

loading...
Graffino

Ruby's .times in JavaScript

Nick Ciolpan
I have extensive experience as a full stack developer, managing clients and building state of the art platforms.
・1 min read

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

Discussion (0)