- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a chained operation class in JavaScript
Problem
We are supposed to create a user defined data type Streak in JavaScript that can be chained to any extent with value and operations alternatively
The value can be one of the following strings −
→ one, two three, four, five, six, seven, eight, nine
The operation can be one of the following strings −
→ plus, minus
For example, if we implement the following in context of our class −
Streak.one.plus.five.minus.three;
Then the output should be −
const output = 3;
Output Explanation
Because the operations that took place are −
1 + 5 - 3 = 3
Example
Following is the code −
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);
Output
Following is the console output −
3
Advertisements
To Continue Learning Please Login
Login with Google