Last active
February 4, 2017 11:38
-
-
Save railsstudent/82c1b71edb2cb8e3b2a902c48f8a048f 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
calc = (expr) -> | |
# Your awesome code here | |
if expr is "" then return 0 | |
stack = [] | |
tokens = expr.split(' ') | |
for token in tokens | |
if token in ['+','-', '*', '/'] | |
# pop the last two values, calculate the total and push the result back | |
operands = stack.splice(stack.length - 2, 2) | |
result = 0 | |
if token is '+' then result = operands[0] + operands[1] | |
if token is '-' then result = operands[0] - operands[1] | |
if token is '*' then result = operands[0] * operands[1] | |
if token is '/' then result = operands[0] / operands[1] | |
stack.push result | |
else | |
# push the value in stack | |
stack.push (Number(token)) | |
# return the last value in stack | |
stack[stack.length - 1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment