skip to Main Content

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 figureout how plus() and equalto() will work.

2

Answers


  1. Sorry I edited this answer . I have misunderstood the question . I think this is what you are looking for right ? So for starter you can do something like this

    function NumberWrapper(value) {
      this.value = value || 0;
    }
    
    NumberWrapper.prototype.plus = function (num) {
      this.value += num;
      return this;
    };
    
    NumberWrapper.prototype.equalTo = function () {
      return this.value;
    };
    
    function one() {
      return new NumberWrapper(1);
    }
    
    function two() {
      return new NumberWrapper(2);
    }
    
    // Usage example
    const result = one().plus().two().equalTo();
    
    console.log(result); // Output: 3
    

    to make it more dynamic you can use for loop and create a wrapper of those number

    for e.g 100’s of them

    
    function createNumberWrapper(value) {
      return {
        plus: function (num) {
          value += num;
          return this;
        },
        equalTo: function () {
          return value;
        }
      };
    }
    
    for (let i = 1; i <= 100; i++) {
      //
    }
    
    Login or Signup to reply.
  2. Here’s a solution using function chaining:

    function one() {
      const fn = this._fn;
      if (!fn)
        this._fn = () => 1;
      else
        this._fn = () => fn(1);
    
      return this;
    }
    
    function two() {
      const fn = this._fn;
      if (!fn)
        this._fn = () => 2;
      else
        this._fn = () => fn(2);
    
      return this;
    }
    
    function plus() {
      const fn = this._fn;
      if (!fn)
        this._fn = n => n;
      else
        this._fn = n => fn() + n;
    
      return this;
    }
    
    function equalTo() {
      const fn = this._fn;
      if (fn) {
        delete this._fn;
        return fn();
      }
      return 0;
    }
    
    
    console.log(one().plus().two().equalTo());                // 3
    console.log(one().plus().two().plus().two().equalTo());   // 5
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search