Last active
August 12, 2016 03:11
-
-
Save DC3/030e5673372a1ee4c1df to your computer and use it in GitHub Desktop.
This file contains 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
operations = | |
'*': (a, b) -> a*b | |
'+': (a, b) -> a+b | |
evaluate = (arr) -> | |
calc = (operation, refArr) -> | |
hasOperation = (index = arr.indexOf(operation)) isnt -1 | |
return refArr unless hasOperation | |
pos = index - 1 | |
[a, op, b] = refArr.splice(pos, 3) | |
result = operations[op](+a, +b) | |
refArr.splice(pos, 0, ''+result) | |
refArr | |
calc('*', arr) while arr.indexOf('*') isnt -1 | |
calc('+', arr) while arr.indexOf('+') isnt -1 | |
if arr.length is 1 | |
results = +arr[0] | |
return results unless isNaN(results) | |
return undefined | |
a = ['10', '+', '20', '*', '3'] | |
b = ['10', '+', '20', '*', '3', '*'] | |
c = ['10', '20', '*', '3'] | |
evaluate(a) | |
evaluate(b) | |
evaluate(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment