Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I chain a javascript method with a value also

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading