Danniell
Danniell

Reputation: 11

Execute Multiple functions in a function

function executeActions(param)
{
    if((param != undefined) && (param.length > 0))
    {
        for(i=0; i < param.length; i++)
        {
            //eval like function
            param[i]();
        }
    }
}

function clearFields()
{
    ...
}

function showAbs(param)
{
    if(param ==  'insert')
    {
        ...
    }
    else if(param  == 'update')
    {
        ...
    }
    else
    {
        ...
    }
}

$("#clearButton").click(function(event)
{
    //var functions = ["clearFields()","showAbs('insert')"];

    var a = showAbs('insert');
    var functions = [clearFields, a];

    executeActions(functions);
});

Hello everyone! How can I execute some functions with parameters in a row in a set of instructions like i've showed above?

If they don't have any parameters, then the functions execute like in chain, but, if one or more of them uses some parameters, it stops with the error: "param[i] is not a function".

Maybe if you have another elegant solution for this code, i'd appreciate if you share with us.

Thank you all in advance!

Upvotes: 1

Views: 1419

Answers (2)

Kenneth
Kenneth

Reputation: 28737

You can use partial application for this. Partial application means that you take a given function and fix one or more parameters to it. Example

function sum(a, b){
    return a + b;
}

function product(a, b){
    return a * b;
}

function doSomething(){
    // do something
}

function runFunctions(funcs){
    for(var i = 0;i<funcs.length;i++){
        funcs[i]();
    }
}


var mySum = function(){
    return sum(5, 6);
}

var myProduct = function(){
    return product(2, 3);
}

runFunctions(mySum, myProduct, doSomething);

The above is using ES 5 syntax. You could make this a bit more concise using ES 6 syntax:

const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something


const runFunctions = funcs => {
    for(func of funcs)
        func();
}


var mySum = () => sum(5, 6);
var myProduct = () => product(2, 3);

runFunctions(mySum, myProduct, doSomething);

or you could use the bind function to take care of fixing the vars:

const sum = (a, b) => a + b;
const product = (a, b) => a * b;
const doSomething = () => // do something


const runFunctions = funcs => {
    for(func of funcs)
        func();
}

runFunctions(sum.bind(null, 5,6), myProduct.bind(null, 2,3), doSomething);

Upvotes: 1

Łukasz Blaszyński
Łukasz Blaszyński

Reputation: 1565

For me a way you want to achieve may be not readable for other developers. You may create a function that will group all your function executions like:

function groupedFunctions{
    return {
       A: funcA(param),
       B: funcB(param),
       C: funcC(param)
    }
}

function executeActions(funcObj, params) {
   funcObj.A(params.a);
   funcObj.B(params.b);
}

let params = {a: 1, b:2}
executeActions(groupedFunction(), params)

Upvotes: 0

Related Questions