IzhanVarsky

Untitled

Mar 24th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. "use strict";
  2.  
  3. const VARIABLES = {"x": 0, "y": 1, "z": 2};
  4.  
  5. function newOperation(action, symbol) {
  6.     function Operation(...args) {
  7.         this.operands = args;
  8.     }
  9.  
  10.     Operation.prototype.toString = function () {
  11.         return this.operands.join(" ") + " " + symbol;
  12.     };
  13.  
  14.     Operation.prototype.evaluate = function (...args) {
  15.         return action(...this.operands.map(operand => (operand.evaluate(...args))));
  16.     };
  17.  
  18.     return Operation;
  19. }
  20.  
  21. function Const(x) {
  22.     this.value = x;
  23. }
  24.  
  25. Const.prototype.toString = function () {
  26.     return this.value.toString();
  27. };
  28.  
  29. Const.prototype.evaluate = function () {
  30.     return this.value;
  31. };
  32.  
  33. function Variable(s) {
  34.     this.name = s;
  35.     this.index = VARIABLES[s];
  36. }
  37.  
  38. Variable.prototype.toString = function () {
  39.     return this.name;
  40. };
  41. Variable.prototype.evaluate = function (...args) {
  42.     return args[this.index];
  43. };
  44.  
  45. const Add = newOperation((a, b) => a + b, "+");
  46. const Subtract = newOperation((a, b) => a - b, "-");
  47. const Multiply = newOperation((a, b) => a * b, "*");
  48. const Divide = newOperation((a, b) => a / b, "/");
  49. const Negate = newOperation(a => -a, "negate");
  50. const Min3 = newOperation((a, b, c) => Math.min(a, b, c), "min3");
  51. const Max5 = newOperation((a, b, c, d, e) => Math.max(a, b, c, d, e), "max5");
Advertisement
Add Comment
Please, Sign In to add comment