So if I want to do something like five().plus().five().equals() // this should return 10 How can I achieve this? I understand method chaining when the functions return another function but what about when you want to use a value in the next function in the chain?
Asked
Active
Viewed 567 times
1
-
Chaining requires the method to return an object, not a function, because you're calling methods of the object. – Barmar Nov 23 '21 at 17:21
-
1Return an object with those methods as properties. Then return the final numeric value with `equals` – evolutionxbox Nov 23 '21 at 17:21
-
You're thinking of something like `add(5)(5)` – Barmar Nov 23 '21 at 17:22
-
@Barmar that's currying right? – evolutionxbox Nov 23 '21 at 17:23
-
yes @Barmar but I want to do it like the way above – travelingengineer Nov 23 '21 at 17:23
-
@evolutionxbox Yes, that's correct. – Barmar Nov 23 '21 at 17:23
-
@travelingengineer Which way? Your question, or my comment? – Barmar Nov 23 '21 at 17:24
-
See https://stackoverflow.com/questions/31306312/javascript-function-challenge-add1-2-and-add12-both-should-return-3 for currying. – Barmar Nov 23 '21 at 17:25
-
So my question was incorrect I think I want to just do five().plus().five().equals() <- should return 10 by returning object also without adding parameters in. – travelingengineer Nov 23 '21 at 17:26
-
1something like `number(5).plus(number(5)).equals()` might be easier? – evolutionxbox Nov 23 '21 at 17:32
2 Answers
3
class Stack{
constructor(state=0){
this.state = state;
this.op = null;
}
pushVal(v){
switch(this.op){
case '+': this.state += v; break;
case '-': this.state -= v; break;
default: this.state = v; break;
}
}
plus(){
this.op = '+';
return this;
}
minus(){
this.op = '-';
return this;
}
equals(){
return this.state;
}
}
consts = {
five: 5,
six: 6,
seven: 7
};
for(const n in consts){
Stack.prototype[n] = function (){
this.pushVal(consts[n])
return this;
}
}
five = () => new Stack(5)
/// Now we can run what you want
console.log(five().plus().five().equals())
// and some extension of it
console.log(five().plus().five().minus().seven().equals())

Bob
- 13,867
- 1
- 5
- 27
2
Chaining
is a Concept in JS in which we can repeatedly call the properties of an object.
What you can do, if it is just about chaining,
let obj = {
num:0,
get(){
console.log(this.num);
return this;
},
set(num){
this.num = num;
return this;
},
add(a){
this.num = this.num+a;
return this;
},
subtract(a){
this.num = this.num-a;
return this;
},
divide(a){
this.num = this.num/a;
return this;
},
multiply(a){
this.num = this.num*a;
return this;
}
}
obj.set(5).add(2).multiply(3).divide(7).add(3).get();
The most important part in chaining is
returning this
You can read more about it at: https://medium.com/technofunnel/javascript-function-chaining-8b2fbef76f7f

Himanshu Singh
- 1,803
- 3
- 16
-
I approve the avoidance of any `five` function, opting for numbers to be passed as parameters instead – Gershom Maes Nov 23 '21 at 17:38