mkHun
mkHun

Reputation: 5927

Add values on subsequent call in javascript function.?

Let's consider I have the following function call,

function add(){
    x = 0 ;
    for(i = 0 i < ##; i++){ // need to run a loop four times
    x+=1
    }
}

Let's consider I am trying to Implement the function that will add one on each subsequent call, like below

console.log(add()()().getValue()); // 3
console.log(add().getValue()); // 1
console.log(add()().getValue()); // 2

Upvotes: 0

Views: 577

Answers (3)

Simon Leroux
Simon Leroux

Reputation: 477

I think you are trying to emulate the behavior of generator functions. Here is a snippet that illustrates one way you could do it with a generator.

function* adder() {
  let x = 0;
  while (true) {
    yield x + 1;
    x++;
  }
}

const add = adder();

const firstValue = add.next();

const secondValue = add.next();

const thirdValue = add.next().value;

Upvotes: -1

epascarello
epascarello

Reputation: 207527

My guess is they were expecting you to use toString() which is not the greatest way of doing this.

function add(x = 0) {
  function next() {
    return add(x+1);
  }
  next.toString = function () {
    return x;
  };
  return next;
}

console.log("example 1", add()()()());
console.log("example 2", add()()()()()()()()());

Upvotes: 1

deceze
deceze

Reputation: 522372

A call to add must return a function which also has a getValue method, and each call to that function must return the same thing. So:

function add() {
    var x = 1;
    
    function inner() {
        x += 1;
        return inner;
    }
    
    inner.getValue = function () {
        return x;
    }
    
    return inner;
}

console.log(add()()().getValue()); // 3
console.log(add().getValue()); // 1
console.log(add()().getValue()); // 2

Upvotes: 4

Related Questions