Search code examples
javascriptmethodschaining

Method chaining with Javascript - Plus Minus Question


I got a code challenge that create a plus-minus functions using method chaining. i have created the code as follows but it eventually failed when it comes to the output rendering like plus(3).minus(2).value() and minus(3).minus(3).value() kind of method invoking

code as follows

function plus(valuez)
    {
      this.valuez = this.valuez+ valuez;
        function value{
            return  valuez
        }
      
        plus.minus = minus;
          plus.value = value;
         plus.plus = this;

        return this;
    }


  function minus(valuez)
    {
       this.valuez = this.v+ valuez;
        function value(){
            return  valuez
        }
        minus.plus = plus;
        minus.minus = this
        minus.value = value;

        return this;
    }

expected output is 1 and 6 but I only get the printed last number entered. how can I resolve this?


Solution

  • class Box {
      constructor(v) { this._value = v }
      plus(v) { this._value += v; return this; }
      minus(v) { this._value -= v; return this; }
      value() { return this._value; } 
    }
    function plus(v) { return new Box(v) }
    function minus(v) { return new Box(-v) }
    
    console.log("plus(3).minus(2).value()", plus(3).minus(2).value());
    console.log("minus(3).minus(3).value()", minus(3).minus(3).value());
     


    function plus (x) { return { _value: x, plus(y){ return plus(this._value+y) }, minus(y){ return plus(this._value-y) }, value(){ return this._value } } }
    function minus(x) { return plus(-x) }
    console.log("plus(3).minus(2).value()", plus(3).minus(2).value());
    console.log("minus(3).minus(3).value()", minus(3).minus(3).value());


    Using closure

    function plus (x) { return { plus(y){ return plus(x+y) }, minus(y){ return plus(x-y) }, value(){ return x } } }
    function minus(x) { return plus(-x) }
    console.log("plus(3).minus(2).value()", plus(3).minus(2).value());
    console.log("minus(3).minus(3).value()", minus(3).minus(3).value());