Creating a chained operation class in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are supposed to create a user defined data type Streak in JavaScript that can be chained to any extent with value and operations alternatively

The value can be one of the following strings −

→ one, two three, four, five, six, seven, eight, nine

The operation can be one of the following strings −

→ plus, minus

For example, if we implement the following in context of our class −

Streak.one.plus.five.minus.three;

Then the output should be −

const output = 3;

Output Explanation

Because the operations that took place are −

1 + 5 - 3 = 3

Example

Following is the code −

 Live Demo

const Streak = function() {
   let value = 0;
   const operators = {
      'plus': (a, b) => a + b,
      'minus': (a, b) => a - b
   };
   const numbers = [
      'zero', 'one', 'two', 'three', 'four', 'five',
      'six', 'seven', 'eight', 'nine'
   ];
   Object.keys(operators).forEach((operator) => {
      const operatorFunction = operators[operator];
      const operatorObject = {};
      numbers.forEach((num, index) => {
         Object.defineProperty(operatorObject, num, {
            get: () => value = operatorFunction(value, index)
         });
      });
      Number.prototype[operator] = operatorObject;
   });
   numbers.forEach((num, index) => {
      Object.defineProperty(this, num, {
         get: () => {
            value = index;
            return Number(index);
         }  
      });
   });
};
const streak = new Streak();
console.log(streak.one.plus.five.minus.three);

Output

Following is the console output −

3
raja
Published on 21-Apr-2021 12:45:08
Advertisements