Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript for-loop alternative: repeat(n, function(i) { ... });

This is the regular for-loop:

for (var i = 0; i < n; i++) { ... }

It is used to iterate over arrays, but also to just repeat some process n times.

I use the above mentioned form, but it repulses me. The header var i = 0; i < n; i++ is plain ugly and has to be rewritten literally every time it is used.

I am writing this question because I came up with an alternative:

repeat(n, function(i) { ... });

Here we use the repeat function which takes two arguments:
1. the number of iterations,
2. a function which body represents the process that is being repeated.

The "code-behind" would be like so:

function repeat(n, f) {
    for (var i = 0; i < n; i++) {
        f(i);
    }
} 

(I am aware of the performance implications of having two additional "levels" in the scope chain of the process)

BTW, for those of you who use the jQuery library, the above mentioned functionality can be achieved out-of-the-box via the $.each method like so:

$.each(Array(n), function(i) { ... });  

So what do you think? Is this repeat function a valid alternative to the native for loop? What are the down-sides of this alternative (other than performance - I know about that)?

Native:

for (var i = 0; i < 10; i++) {
    // do stuff
}

Alternative:

repeat(10, function(i) {
    // do stuff
});
like image 615
Šime Vidas Avatar asked Feb 08 '11 02:02

Šime Vidas


2 Answers

You say you want a revolution... Well, you know: ruby did it just before (?)

Number.prototype.times = function(func) { 
    for(var i = 0; i < Number(this); i++) {
        func(i); 
    }
}

means

(50).times(function(i) {
    console.log(i)
})

Anyway, don't fight against C, you'll always lose :-P

like image 55
Gonzalo Larralde Avatar answered Sep 19 '22 23:09

Gonzalo Larralde


it's an interesting thought, but if you dislike the syntax for the loop, you could always do a different type of loop:

var i = arr.length; 
while (i--) {
    // do stuff
}

the reverse while loop is generally faster than a for loop as well.

like image 43
Jeff Avatar answered Sep 19 '22 23:09

Jeff