Calculator-codewards-js

原题链接: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
            }
        };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值