Skip to content

Instantly share code, notes, and snippets.

@marsgpl
Last active March 12, 2019 23:12
Show Gist options
  • Save marsgpl/f450bf36e4d47415e26eb36020dbc0c6 to your computer and use it in GitHub Desktop.
Save marsgpl/f450bf36e4d47415e26eb36020dbc0c6 to your computer and use it in GitHub Desktop.
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