在 JavaScript 中创建一个链式操作类
问题
我们应该在JavaScript中创建一个用户定义的数据类型Streak,它可以链接到任意程度的值 和操作 交替进行
该值可以是以下字符串之一-
→ one, two three, four, five, six, seven, eight, nine
该操作可以是以下字符串之一-
→ plus, minus
例如,如果我们在类的上下文中实现以下内容-
Streak.one.plus.five.minus.three;
那么输出应该是-
const output = 3;
输出说明
因为发生的操作是-
1 + 5 - 3 = 3
示例
以下是代码-
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);输出结果
以下是控制台输出-
3