Skip to content

Instantly share code, notes, and snippets.

@DC3
Last active August 12, 2016 03:11
Show Gist options
  • Save DC3/030e5673372a1ee4c1df to your computer and use it in GitHub Desktop.
Save DC3/030e5673372a1ee4c1df to your computer and use it in GitHub Desktop.
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