Last active
March 12, 2019 23:12
-
-
Save marsgpl/f450bf36e4d47415e26eb36020dbc0c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const example = "(2+2.0) *2" | |
const calculator = expr => { | |
while ( expr.match(/\(/) ) { | |
expr = expr.replace(/\(([^\)]+)\)/g, (_,subExpr) => calculator(subExpr)) | |
} | |
while ( expr.match(/[\*\/]/) ) { | |
expr = expr.replace(/([0-9\.]+)\s*([\*\/])\s*([0-9\.]+)/g, calculator.process) | |
} | |
while ( expr.match(/[\+\-]/) ) { | |
expr = expr.replace(/([0-9\.]+)\s*([\+\-])\s*([0-9\.]+)/g, calculator.process) | |
} | |
return expr | |
} | |
calculator.process = (_, x, op, y) => { | |
x = parseFloat(x) | |
y = parseFloat(y) | |
switch (op) { | |
case "+": return x + y | |
case "-": return x - y | |
case "*": return x * y | |
case "/": return x / y | |
default: return NaN | |
} | |
} | |
console.log(calculator(example)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment