Home >Web Front-end >JS Tutorial >Create chained action classes in JavaScript

Create chained action classes in JavaScript

PHPz
PHPzforward
2023-09-17 12:13:081208browse

在 JavaScript 中创建链式操作类

Question

We should create a user-defined data type Streak in JavaScript that can be associated with values and Action Link to any scope 强> or

The value can be one of the following strings -

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

The action can be one of the following strings -

→ plus, minus

For example, if we implement the following in the context of a class -

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

then the output should be -

const output = 3;

Output explanation

because the operations that occur are -

1 + 5 - 3 = 3

Example

The following is the code-

Real-time demonstration

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

The following is the console output-

3

The above is the detailed content of Create chained action classes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete