What is the most efficient way to create map of functions to arguments?

前端 未结 4 2049
我寻月下人不归
我寻月下人不归 2021-01-07 04:32

I want to create a map of functions to its argument. This map will be updated dynamically. Finally all the functions will be called with their corresponding arguments.

4条回答
  •  情书的邮戳
    2021-01-07 04:51

    Credits to Dagg Nabbit for suggesting this in the comments under my question.

    "Don't forget functions can have properties. You could always store the functions in an array, and attach their index in the array to the function as a propery, and look them up that way." - Dagg Nabbit

    Consider the following map of args-to-callback arguments :

    map :

    1 -> foo1
    2 -> foo1,foo2
    3 -> foo2
    

    The objective is to construct a callback-to-args map (reverse map) like this :

    callbackMap:

    foo1 -> [1,2]
    foo2 -> [2,3]
    

    Approach :

    var allArgsPossible = [1,2,3]
    
    // contains the list of callbacks to be called
    var callbackArray = [];  
    
    //maps the callback index in callbackArray to the callback's arguments
    //callbackMap[index] = args means callbackArray[index] will be called with parameter "args" 
    var callbackMap = {};
    
    for( i in allArgsPossible)
    {
        var item = allArgsPossible[i];
        var callbacks =  map[ item  ];
        for(j in callbacks)
        {
            var callback = callbacks[j];
    
            if(callback.index == undefined)
            {
                var index = callbackArray.length;
                // adding a new property "index" to the callback
                callback.index = index;
                callbackMap[index] = [item];
                //create a new entry in callbackArray
                callbackArray.push(callback);
            }
            else
            {
                callbackMap[callback.index].push(item);
            }
        }
    }
    
    console.log(JSON.stringify(callbackMap));
    
    for( i in callbackArray)
    {
        var callback = callbackArray[i];
        //get arguments from our reverse map
        var args = callbackMap[callback.index];
        // Bingo ! 
        callback(args);
    }
    

    You can get the whole picture here : http://jsfiddle.net/kyvUA/2/

    One point to note here is that the callback function may already have an "index" property for some other purpose. If that is a concern, you can generate a random string and store this property on the callback with the index as the value. ( as suggested by @plalx )

    Cheers !

提交回复
热议问题