原题链接:https://www.codewars.com/kata/5235c913397cbf2508000048
问题描述:
Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression
- Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.、
- Example: `Calculator().evaluate(“2 / 2 + 3 * 4 - 6”) # => 7
翻译:创建一个有加减乘除功能的计算器函数,乘除优先级高于加减,从左到右进行计算。
我的代码:
const Calculator = function() {
this.evaluate = string => {
let arr = string.split(' ')
let res = []
let a
for (let i = 0; i < arr.length; i++) {
res.push(arr[i])
if (arr[i] == '*') {
a = (res[res.length - 2] - 0) * (arr[i + 1] - 0)
res.pop()
res.pop()
res.push(a)
i++
}
if (arr[i] == '/') {
a = (res[res.length - 2] - 0) / (arr[i + 1] - 0)
res.pop()
res.pop()
res.push(a)
i++
}
}
let b = res[0] - 0
for (let i = 0; i < res.length; i++) {
if (res[i] == '+') b += (res[i + 1] - 0)
if (res[i] == '-') b -= (res[i + 1] - 0)
}
return b
}
};
大神从不让人失望
const Calculator = function() {
this.evaluate = string => {
let mult = /(\S+) (\*|\/) (\S+)/
let Add = /(\S+) (\+|-) (\S+)/
while (mult.test(string)) {
string = string.replace(mult, (_, num1, operator, num2) => (operator === "*") ? num1 * num2 : num1 / num2)
}
while (Add.test(string)) {
string = string.replace(Add, (_, num1, operator, num2) => (operator === "+") ? +num1 + +num2 : num1 - num2)
}
return string
}
};