在 JavaScript 中建立鏈式操作類
問題
我們應該在 JavaScript 中建立一個使用者定義的資料型別 Streak,它可以與任何範圍value 和operations 交替連結
值可以是以下字串之一 −
→ 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP