Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating a chained operation class in JavaScript
This article demonstrates how to create a fluent interface class in JavaScript that allows chaining numeric values and mathematical operations. The Streak class enables natural language-like mathematical expressions.
Problem
We need to create a custom data type Streak in JavaScript that supports method chaining with values and operations alternately.
The supported values are:
? one, two, three, four, five, six, seven, eight, nine
The supported operations are:
? plus, minus
For example, this expression:
Streak.one.plus.five.minus.three;
Should evaluate to:
3
How It Works
The calculation follows natural order: 1 + 5 - 3 = 3
Implementation
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
Key Components
Property Getters: Each number name creates a getter that sets the current value and returns a Number object for chaining.
Operator Objects: Operations like plus and minus are added to Number.prototype, containing getters for each number that perform the calculation.
Fluent Interface: The chaining works because each step returns an object that has the next expected properties available.
Example with Multiple Operations
const streak = new Streak(); console.log(streak.seven.minus.two.plus.four); // 7 - 2 + 4 = 9 console.log(streak.nine.minus.three.minus.one); // 9 - 3 - 1 = 5
9 5
Conclusion
This implementation demonstrates advanced JavaScript concepts like property getters, prototype modification, and fluent interfaces. The Streak class provides an intuitive way to perform chained mathematical operations using natural language syntax.
