在方法中插入运算符

问题描述

任务是编写一个 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)`)
}

除了严格禁止使用的 eval()之外,是否可以在 reduce()方法中插入函数参数 operator ? / p>

解决方法

不确定这个问题,但是您可以将所有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,val)=>res*val) // 4914

现在,您可以通过任何内容。像模或幂等。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...