Abstracting some two deep loop procedure

72 views Asked by At

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.

1

There are 1 answers

2
Hrishi On BEST ANSWER

You could use inner functions to accomplish what you are describing, so, if the function traverse takes a parameter based on which the functions A, B and C get defined, define them by writing a function inside the traverse 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:

function traverse(param) {

   function defineProcedures(args) {
      /* local vars which have function scope(visible to the entire defineProcedures 
         body
      */
     var funcA = function(params) { //blah };
     var funcB = function(params) { //blah };
     var funcC = function(params) { //blah };

      return [funcA, funcB, funcC];
  }
  var procs = defineProcedures(param);
  var firstFunc = procs[0],
      secondFunc = procs[1],
      thirdFunc = procs[2];

  //for loops go here and invoke the functions appropriately.

}