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;
because the operations that occur are -
1 + 5 - 3 = 3
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);
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!