Search code examples
javascriptcyclesimplify

Simplify the code by using cycle function


I have multiply functions which are using the same cycle code and i'm wondering is it possible to simplify the code by having one cycle function so i could execute the code just by calling wanted function names.

Now:

for(var i=0;i<all;i++){ someFunction(i) }

Need:

cycle(someFunction);
function cycle(name){
    for(var i=0;i<all;i++){
       name(i);
    }
}

I tried to do this by using "window" and i get no error but the function is not executed.

var MyLines = new lineGroup();
MyLines.createLines(); // works
MyLines.addSpeed();    // doesn't work


var lineGroup = function(){
    this.lAmount = 5,
    this.lines = [],

    this.createLines = function (){
        for(var i=0,all=this.lAmount;i<all;i++){
            this.lines[i] = new line();
        }
    },

    this.addSpeed = function (){
        // no error, but it's not executing addSpeed function
        // if i write here a normal cycle like in createLines function
        // it's working ok
        this.linesCycle("addSpeed");
    },
    this.linesCycle = function(callFunction){
        for(var i=0,all=this.lAmount;i<all;i++){
            window['lineGroup.lines['+i+'].'+callFunction+'()'];
        }
    }
}

var line = function (){
    this.addSpeed = function (){
        console.log("works");
    }
}

Solution

  • window['lineGroup.lines['+i+'].'+callFunction+'()'];
    

    literally tries to access a property that starts with lineGroups.lines[0]. Such a property would only exist if you explicitly did window['lineGroups.lines[0]'] = ... which I'm sure you didn't.

    There is no need to involve window at all. Just access the object's line property:

    this.lines[i][callFunction]();
    

    i get no error but the function is not executed.

    Accessing a non-existing property doesn't generate errors. Example:

    window[';dghfodstf0ap9sdufgpas9df']

    This tries to access the property ;dghfodstf0ap9sdufgpas9df, but since it doesn't exist, this will result in undefined. Since nothing is done with the return value, no change can be observed.