Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save TGOlson/31255cd2ae17a6e6fa1d to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/31255cd2ae17a6e6fa1d to your computer and use it in GitHub Desktop.
Functional RPN Calc
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