gpt4 book ai didi

javascript - 如果存在无法识别的运算符 javascript,则返回一个值

转载 作者:行者123 更新时间:2023-12-03 00:08:55 26 4
gpt4 key购买 nike

我有一个代码可以识别数组中的运算符并使用它来基于另一个数组进行计算。下面是代码

function interpret(...args) {
let operators = args[1]; //get the operators array
let values = args[2] //numbers expect the first one.
return values.reduce((ac, val, i) => {
//check the operator at the 'i' on which we are on while iterating through 'value'
if (operators[i] === '+') return ac + val;
if (operators[i] === '-') return ac - val;
if (operators[i] === '*') return ac * val;
if (operators[i] === '/') return ac / val;
else return -1;
}, args[0]) //'ac' is initially set to first value.
}

console.log(interpret(1, ["+"], [1]))
console.log(interpret(4, ["-"], [2]))
console.log(interpret(1, ["+", "*"], [1, 3]))
console.log(interpret(5, ["+", "*", "-"], [4, 1, 3]))
console.log(interpret(10, ['*', '$', '+'], [5, 3, 2])) //It fails in this case and gives 1

请帮助解决此问题。谢谢

最佳答案

您可以设置一个标志,例如invalid,这样您的reduce函数仅在发现无效运算符时返回-1:

function interpret(...args) {
let operators = args[1]; //get the operators array
let invalid = false; // no invalid operators
let values = args[2] //numbers expect the first one.
return values.reduce((ac, val, i) => {
//check the operator at the 'i' on which we are on while iterating through 'value'
if (!invalid) { // if invalid is false then:
if (operators[i] === '+') return ac + val;
if (operators[i] === '-') return ac - val;
if (operators[i] === '*') return ac * val;
if (operators[i] === '/') return ac / val;
}
// If invalid is true or the above operators did not match, then
invalid = true; // this will only be set to true if the above if statments didn't run
return -1 // return -1 (this will always be executred from now on as the if(!invalid) will not run the code within it anymore

}, args[0]) //'ac' is initially set to first value.
}

console.log(interpret(1, ["+"], [1]))
console.log(interpret(4, ["-"], [2]))
console.log(interpret(1, ["+", "*"], [1, 3]))
console.log(interpret(5, ["+", "*", "-"], [4, 1, 3]))
console.log(interpret(10, ['*', '$', '+'], [5, 3, 2])) // -1

或者,您可以使用新方法来实现此目的,例如递归解决方案:

const oper = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => a / b
};

const interpret = (n, [fc, ...calcs], [fn, ...nums]) => {
if(fc === undefined) return n;
if(!(fc in oper)) return -1;
return interpret(oper[fc](n, fn), calcs, nums)
}

console.log(interpret(1, ["+"], [1]))
console.log(interpret(4, ["-"], [2]))
console.log(interpret(1, ["+", "*"], [1, 3]))
console.log(interpret(5, ["+", "*", "-"], [4, 1, 3]))
console.log(interpret(10, ['*', '$', '+'], [5, 3, 2])) // -1

关于javascript - 如果存在无法识别的运算符 javascript,则返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com