Search code examples
javascriptthisnew-operator

How to create a fluent chaining equation solver that can work `one().plus().two().equalTo()`


I have been given a task at my internship , I have to create math operations like plus(), minus() etc. using this and new keywords.

example: one().plus().two().equalTo() , given line of code must return 3.

I tried creating functions which returns values.

function one(){
    return 1;
}

But I am not able to figure out how plus() and equalTo() will work.


Solution

  • Here's a solution using function chaining:

    const numbering = (fn, n) => () => fn?.(n) ?? n;
    
    function one() {
      this._fn = numbering(this._fn, 1);
      return this;
    }
    
    function two() {
      this._fn = numbering(this._fn, 2);
      return this;
    }
    
    function plus() {
      const fn = this._fn;
      this._fn = n => (fn?.() ?? 0) + n;
      return this;
    }
    
    function equalTo() {
      const fn = this._fn;
      delete this._fn;
      return fn?.() ?? 0;
    }
    
    
    console.log(one().plus().two().equalTo());                // 3
    console.log(one().plus().two().plus().two().equalTo());   // 5