Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda