lwzm
9/29/2014 - 2:09 AM

Tiny RPN calculator, written by coffeescript.

Tiny RPN calculator, written by coffeescript.

#!/usr/bin/env coffee
# Usage:
# $ ./rpn_calc.coffee '8 8 * 2 2 + / 3 * 6 -'
# 42
#
# Suggested Reading:
# http://www.busybox.net/downloads/BusyBox.html#dc
#

print = console.log.bind(console)

add = (a, b) -> a + b
sub = (a, b) -> a - b
mul = (a, b) -> a * b
div = (a, b) -> a / b
mod = (a, b) -> a % b
pow = (a, b) -> a ** b

operators =
    add: add
    "+": add
    sub: sub
    "-": sub
    mul: mul
    "*": mul
    div: div
    "/": div
    mod: mod
    "%": mod
    pow: pow
    "**": pow


calc = (s) ->
    stack = []
    for x in s.trim().split(/\s+/)
        n = Number(x)
        if isNaN(n)
            b = stack.pop()
            a = stack.pop()
            stack.push(operators[x](a, b))
        else
            stack.push(n)
    stack.pop()


for s in process.argv.slice(2)
    print(calc(s))