ปัญหา
เราควรจะสร้าง Streak ประเภทข้อมูลที่กำหนดโดยผู้ใช้ใน JavaScript ที่สามารถเชื่อมโยงกับขอบเขตใดก็ได้ด้วย ค่า และ ปฏิบัติการ หรืออีกทางหนึ่ง
ค่าสามารถเป็นหนึ่งในสตริงต่อไปนี้ -
→ 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