In my project I have to do some two-deep loop procedure several (meaning a lot of) times. I'll have to do the same:
for (var i = 0; i < length; i++) {
something_here_maybe;
for (var j = 0; j < second_length; j++) {
something_else_here;
}
perhaps_other_thing_here;
}
Now I don't want to keep doing that, so I tried some:
function traverse(before, inside, after) {
for (var i = 0; i < length; i++) {
(before) ? before(i) : null;
for (var j = 0; j < second_length; j++) {
(inside) ? inside(i, j) : null;
}
(after) ? after(i) : null;
}
}
Of course, that seemed much more desirable for me, given that I thought I could do something like:
traverse(function(x) { blabla; }, function(x, y) { blabla; }, function(x) { blabla; });
Mbut ... I simply got to the point where those three functions need to interact with one another. And the variables in them are local - so they can't interact. I'd need to define those variables in traverse(), but I don't know beforehand what variables I'll need. I'd try to define another "initialize" parameter in traverse (as the first argument) which would be a function that initializes those values. But it would still be a function, and those variables would still be local to it, not taken by traverse();
Could you help me with any ideas about this approach ? Or it simply can't be done ? Any idea or advice would be much appreciated. Thank you in advance.
You could use inner functions to accomplish what you are describing, so, if the function
traverse
takes a parameter based on which the functionsA
,B
andC
get defined, define them by writing a function inside thetraverse
function which returns the three functions as it's return value, (you can return an array with the three functions in them) and then invoke the three functions in your loop.example: