Advertisement
reiziger

Untitled

Mar 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. const abstractOperation = operation => (...operands) => (...values) => {
  2. let result = [];
  3. for (operand of operands) {
  4. result.push(operand(...values));
  5. }
  6.  
  7. return operation(...result);
  8. }
  9.  
  10. const variables = ['x', 'y', 'z'];
  11.  
  12. const variable = name => {
  13. let index = variables.indexOf(name);
  14. return (...values) => values[index];
  15. };
  16.  
  17. const cnst = value => () => value;
  18.  
  19. const add = abstractOperation((a, b) => a + b);
  20.  
  21. const subtract = abstractOperation((a, b) => a - b);
  22.  
  23. const multiply = abstractOperation((a, b) => a * b);
  24.  
  25. const divide = abstractOperation((a, b) => a / b);
  26.  
  27. const negate = abstractOperation(a => -a);
  28.  
  29. const abs = abstractOperation(a => Math.abs(a));
  30.  
  31. const iff = abstractOperation((a, b, c) => a >= 0 ? b : c);
  32.  
  33. const avg5 = abstractOperation((...operands) => {
  34. let sum = operands.reduce((sum, currentSum) => sum + currentSum);
  35. return sum / operands.length;
  36. });
  37.  
  38. const med3 = abstractOperation((...operands) => {
  39. operands.sort((a, b) => a- b);
  40. return operands[1];
  41. });
  42.  
  43. const pi = cnst(Math.PI);
  44.  
  45. const e = cnst(Math.E);
  46.  
  47. const one = cnst(1);
  48.  
  49. const two = cnst(2);
  50.  
  51.  
  52. function isDigit(character) {
  53. return character >= "0" && character <= "9";
  54. }
  55.  
  56. const operations = {
  57. '+' : [add, 2],
  58. '-' : [subtract, 2],
  59. '*' : [multiply, 2],
  60. '/' : [divide, 2],
  61. 'negate' : [negate, 1],
  62. 'abs' : [abs, 1],
  63. 'iff' : [iff, 3],
  64. 'med3' : [med3, 3],
  65. 'avg5' : [avg5, 5]
  66. };
  67.  
  68. const constants = {
  69. 'pi' : pi,
  70. 'e' : e,
  71. 'one' : one,
  72. 'two' : two
  73. }
  74.  
  75. const vars = {
  76. "x" : variable("x"),
  77. "y" : variable("y"),
  78. "z" : variable("z")
  79. }
  80.  
  81. const parse = expression => (...values) => {
  82. let tokens = expression.split(/\s+/);
  83. let stack = [];
  84. tokens.map(function(token) {
  85. if (token in operations) {
  86. let args = [];
  87. let len = stack.length;
  88. stack.slice(len - operations[token][1], len).forEach(function () {
  89. args.push(stack.pop());
  90. });
  91. args.reverse();
  92. stack.push(operations[token][0](...args));
  93. } else if (isDigit(token[0]) || (token[0] === '-' && token.length !== 1)) {
  94. stack.push(cnst(parseInt(token)));
  95. } else if (token in vars) {
  96. stack.push(vars[token]);
  97. } else if(token in constants) {
  98. stack.push(constants[token]);
  99. }
  100. })
  101.  
  102. return stack.pop()(...values);
  103. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement