Search code examples
javascriptparameter-passingfunction-parameter

Javascript function call with another function as parameter


I have a few functions in two different files that are all linked together by function calls they are as follows

FILE 1:

function getFunction(func){

}   

FILE 2:

function Numbers(one, two) {
    return (one*two);
}


var func = getFunction(Numbers);

and these are called by:

func(input_array);

my array has values 1,3,5,7,9 and I need func(input_array) to return 3,15,35,63,9 (the last value loops back to the first value)

basically what I am trying to do is have getFunction return a function such that these values are calculated. I am having trouble because I can't wrap my mind about sending and returning functions. I don't know how to access the array if it isn't sent into the function. Let me know if I need to clarify anything.


Solution

  • function getFunction(callback) {
        return function(array) {
            return array.map(function(cur, index) {
                return callback(cur, array[(index+1) % array.length]);
            });
        };
    }
    

    getFunction returns a closure over the callback parameter, which is the function that you want to call. The closure receives the array parameter, and it calls the callback in a loop over the array using array.map. The % modulus operator performs the wraparound that you want.

    Another way to write this that may be clearer is:

    function getFunction(callback) {
        return function(array) {
            var result = [];
            for (var i = 0; i < array.length; i++) {
                j = (i+1) % array.length; // Next index, wrapping around
                result.push(callback(array[i], array[j]));
            }
            return result;
        };
    }
    
    var func = getFunction(Numbers);
    console.log(func([1,3,5,7,9])); // Logs [3,15,35,63,9]