Last active
August 29, 2015 14:20
-
-
Save TGOlson/31255cd2ae17a6e6fa1d to your computer and use it in GitHub Desktop.
Functional RPN Calc
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
| var R = require('ramda'); | |
| var rpn = R.compose(R.head, R.reduce(foldingFn, []), R.split(' ')); | |
| function foldingFn(acc, v) { | |
| if(isOperator(v)) { | |
| var vs = R.take(2, acc), | |
| rest = R.drop(2, acc); | |
| return R.prepend(useOperator(v, vs), rest); | |
| } else { | |
| return R.prepend(parseInt(v), acc); | |
| } | |
| } | |
| var OPERATORS = { | |
| '+': R.add, | |
| '-': R.subtract, | |
| '/': R.divide, | |
| '*': R.multiply | |
| }; | |
| var isOperator = R.partialRight(R.has, OPERATORS); | |
| function useOperator(op, vs) { | |
| var operator = R.prop(op, OPERATORS); | |
| return R.reduce(operator, R.head(vs), R.tail(vs)); | |
| } | |
| rpn('4 2 + 3 *'); | |
| // => 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment