Skip to content

Instantly share code, notes, and snippets.

@QuadFlask
Created April 5, 2016 12:29
Show Gist options
  • Save QuadFlask/917de5723b716802c58adadc22360b5c to your computer and use it in GitHub Desktop.
Save QuadFlask/917de5723b716802c58adadc22360b5c to your computer and use it in GitHub Desktop.
[CodeWars] Reverse polish calc

문자열

1 3 +

을 계산

function calc(expr) {
  if (!expr) return 0;

  var stack = [];
  var op = {
    '+':(a,b)=>a+b,
    '-':(a,b)=>b-a,
    '/':(a,b)=>b/a,
    '*':(a,b)=>a*b
  };

  expr.split(' ').map(s=>parseFloat(s)?parseFloat(s):s).forEach(e=> {
    if (op[e]) stack.push(op[e](stack.pop(),stack.pop()));
    else stack.push(e);    
  });
  return stack.pop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment