Skip to content

Instantly share code, notes, and snippets.

@mikesmullin
Last active March 25, 2017 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesmullin/a6918611ed7abbab8f09d5a5001b4a00 to your computer and use it in GitHub Desktop.
Save mikesmullin/a6918611ed7abbab8f09d5a5001b4a00 to your computer and use it in GitHub Desktop.
Reverse Polish Notation Calculator (in CoffeeScript)
# Reverse Polish Notation Calculator (in CoffeeScript)
# authored by Mike Smullin <mike@smullindesign.com>
#
# see also:
# https://en.wikipedia.org/wiki/Polish_notation
# http://www.calculator.org/rpn.aspx
# http://blog.reverberate.org/2013/07/ll-and-lr-parsing-demystified.html
# http://stackoverflow.com/questions/5975741/what-is-the-difference-between-ll-and-lr-parsing
# https://www.amazon.com/Definitive-ANTLR-4-Reference/dp/1934356999
stack = []
allClear = -> stack.splice 0 # AC
add = (addend, augend) -> augend + addend # = sum
subtract = (subtrahend, minuend) -> minuend - subtrahend # = difference
multiply = (multiplier, multiplicator) -> multiplicator * multiplier # = product
divide = (divisor, dividend) -> dividend / divisor # = quotient
operation = (binaryOperator) -> stack.push binaryOperator stack.pop(), stack.pop()
calc = (equation) ->
for operand in equation.split " "
switch operand
when "+" then operation add
when "-" then operation subtract
when "×", "*" then operation multiply
when "÷", "/" then operation divide
else stack.push parseFloat operand
return stack.pop()
console.log calc "3 15 7 1 1 + - ÷ × 1 1 + 2 + -"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment