Passing a math operator as a parameter

前端 未结 6 1301
长发绾君心
长发绾君心 2021-01-03 18:45

I\'d like to write a function in Javascript that allows me to pass in a mathematical operator and a list of ints and for each item in that list, apply the operator to it.

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 19:01

    If all the operations you are planning to do are binary operations, then you can do this

    var operations = {
        "+" : function (operand1, operand2) {
            return operand1 + operand2;
        },
        "-" : function (operand1, operand2) {
            return operand1 - operand2;
        },
        "*" : function (operand1, operand2) {
            return operand1 * operand2;
        }
    };
    
    function accumulate(list, operator) {
        return list.reduce(operations[operator]);
    }
    
    console.log(accumulate([1, 2, 3, 4], "+"));     // 10
    console.log(accumulate([1, 2, 3, 4], "-"));     // -8
    console.log(accumulate([1, 2, 3, 4], "*"));     // 24
    

提交回复
热议问题