Vấn đề
Chúng ta cần tạo một kiểu dữ liệu do người dùng định nghĩa tên là Streak trong JavaScript có thể được chuỗi (chained) đến bất kỳ mức độ nào với giá trị (value) và phép toán (operations) xen kẽ nhau.
Giá trị có thể là một trong các chuỗi sau:
→ one, two, three, four, five, six, seven, eight, nine
Phép toán có thể là một trong các chuỗi sau:
→ plus, minus
Ví dụ, nếu chúng ta thực hiện sau trong ngữ cảnh của lớp:
Streak.one.plus.five.minus.three;
Thì đầu ra sẽ là:
const output = 3;
Giải thích kết quả
Vì các phép toán diễn ra là:
1 + 5 - 3 = 3
Ví dụ
Dưới đây là mã thực hiện:
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);
Kết quả
Đầu ra trên console:
3