在方法中插入运算符

Insert an operator in a method

任务是写一个函数interpret(arr, operator)获取一个数组并根据operator对其进行归约。

显而易见的解决方案是:

function interpret(arr, operator) {

    switch (operator) {
        case '+' :
            return arr.reduce((a, b) => a + b);
        case '-':
            return arr.reduce((a, b) => a - b);
        case '*':
            return arr.reduce((a, b) => a * b);
        case '/':
            return arr.reduce((a, b) => a / b);
        default:
            throw new Error(`No such command: ${operator}!`);
    }
}

我不喜欢的是几乎相同的表达重复了4次。

马上想到一个解决方案:

function interpret(arr, operator) {
    return eval(`arr.reduce((a, b) => a ${operator} b)`)
}

有没有办法在 reduce() 方法中插入函数参数 operator 而不是严格弃用的 eval()?

不确定这个问题,但您可以将所有这些 case 放在 reduce 中,而不是在 reduce 之前。

function interpret(arr, operator) {
   return arr.reduce((a, b) => {
     switch (operator) {
       case '+' :
         return a+b;
       case '-' :
         return a-b;
       case '*' :
         return a*b;
       case '/' :
         return a/b;
       default:
         throw new Error(`No such command: ${operator}!`)
     }
   })
}

与其每次都进行静态操作,不如尝试传递一个函数,即 reduce 函数的回调本身。像这样。

function interpret(arr,operation){
    return arr.reduce(operation)
}

您可以将其命名为

arr = [3, 3, 546]

interpret(arr, (res,val)=>res+val) //552
interpret(arr, (res,val)=>res*val) // 4914

现在你想传什么就传什么。比如模或幂等。