ปัญหา
เราต้องสร้างชนิดข้อมูลผู้ใช้ Streak ใน JavaScript ที่สามารถเชื่อมโซ่ (chain) ได้ไม่จำกัดกับ ค่า (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