Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
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
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

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()()()()()()()()());

about 4 years ago · Juan Pablo Isaza Denunciar

0

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;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda