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

409
Visualizações
Can I get the current value of generator in JavaScript?

Let's say I want to rotate class names for my button on click. Clicked once becomes button-green, twice - button-yellow, thrice - button-red. And then it repeats, so fourth click makes it button-green again.

I know other techniques how to do it, I'm not asking for implementation advice. I made up this example to understand something about generators in JavaScript.

Here's my code with generator:

function* rotator(items) {
    while (true) {
        for (const item of items) {
            yield item;
        }
    }
}

const classRotator = rotator([
    'button-green',
    'button-yellow',
    'button-red',
]);

document.getElementById('my-button').addEventListener('click', event => {
    event.currentTarget.classList.add(classRotator.next().value);
});

It works fine, except it never gets rid of the previous class. The most convenient way would be to read the current state before getting the next one:

// .current is not a thing:
event.currentTarget.classList.remove(classRotator.current);

Of course I can keep this value on my own and use it. Likewise, I can clear all classes I use in the rotator() myself. I can even make my generator function yield both previous and current value:

function* rotator(items) {
    let previous;

    while (true) {
        for (const item of items) {
            yield {
                item,
                previous
            };

            previous = item;
        }
    }
}

And then use it like this:

document.getElementById('my-button').addEventListener('click', event => {
    const {item: className, previous: previousClassName} = classRotator.next().value;

    event.currentTarget.classList.remove(previousClassName);
    event.currentTarget.classList.add(className);
});

But that's not the point - for educational purpose I'm asking this question:

Can I read the current value of generator function in JavaScript? If not, is it to avoid using memory when it's not needed (this value can potentially be very big)?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Can I read the current value of generator function in JavaScript?

No.

But you can easily implement this yourself if you want to.

If not, is it to avoid using memory when it's not needed?

Maybe. An iterator is supposed to not cling onto the last value it has generated, to allow independent garbage collection and to make it cheap to keep exhausted or not-yet-finished generators around.

But I think the prime reason why there is no .current field available in the design is that it doesn't make sense from a theoretical standpoint: what value would that field have before the iteration started, or after the iterator is exhausted? One could have opted for undefined, but a clean design simply doesn't have the field at all and only returns values if you actually step the iterator.

about 4 years ago · Juan Pablo Isaza Relatório

0

JavaScript "native" APIs generally are willing to create new objects with wild abandon. Conserving memory is generally not, by any appearances, a fundamental goal of the language committee.

It would be quite simple to create a general facility to wrap the result of invoking a generator in an object that delegates the .next() method to the actual result object, but also saves each returned value as a .current() value (or whatever works for your application). Having a .current() is useful, for such purposes as a lexical analyzer for a programming language. The basic generator API, however, does not make provisions for that.

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