daily pastebin goal
8%
SHARE
TWEET

Untitled

a guest Mar 24th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const abstractOperation =
  2.     op => (...operands) => (...values) => op(...operands.map(curOperand => curOperand(...values)));
  3.  
  4. const cnst = value => () => value;
  5.  
  6. const variable = name => (...values) => values[name.charCodeAt(0) - "x".charCodeAt(0)];
  7.  
  8. const add = abstractOperation((a, b) => a + b);
  9.  
  10. const subtract = abstractOperation((a, b) => a - b);
  11.  
  12. const multiply = abstractOperation((a, b) => a * b);
  13.  
  14. const divide = abstractOperation((a, b) => a / b);
  15.  
  16. const negate = abstractOperation(a => -a);
  17.  
  18. const avg5 = abstractOperation((...operands) => operands.reduce((sum, cur) => sum + cur) / operands.length);
  19.  
  20. const med3 = abstractOperation((...operands) =>
  21.     operands.sort((a, b) => a - b)[~~(operands.length / 2)]);
  22.  
  23. const pi = cnst(Math.PI);
  24. const e = cnst(Math.E);
  25.  
  26. const consts = {
  27.     'pi': pi,
  28.     'e': e,
  29. };
  30.  
  31. const vars = {
  32.     'x': variable('x'),
  33.     'y': variable('y'),
  34.     'z': variable('z'),
  35. };
  36.  
  37. const operations = {
  38.     '+': [add, 2],
  39.     '-': [subtract, 2],
  40.     '*': [multiply, 2],
  41.     '/': [divide, 2],
  42.     'negate': [negate, 1],
  43.     'med3': [med3, 3],
  44.     'avg5': [avg5, 5],
  45. };
  46.  
  47. const parse = expression => (...values) => {
  48.     let tokens = expression.split(' ').filter(token => token !== "");
  49.     let stack = [];
  50.     tokens.map(token => {
  51.         if (token in operations) {
  52.             let [op, numberOfArgs] = operations[token];
  53.             stack.push(op(...stack.splice(stack.length - numberOfArgs, numberOfArgs)));
  54.         } else if (token in vars) {
  55.             stack.push(vars[token]);
  56.         } else if (token in consts) {
  57.             stack.push(consts[token]);
  58.         } else {
  59.             stack.push(cnst(Number(token)));
  60.         }
  61.     });
  62.     return stack.pop()(...values);
  63. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top