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

270
Visualizações
Uncaught TypeError: element is undefined when using generator function

I have the following javascript snippet:


/**
 *  Returns the maximal element in the `iterable` as calculated by the given function
 *  @param {Iterable} iterable - iterable to find the maximal element in
 *  @param {function} fn - function to calculate the maximal element
 * 
 *  @returns {any} - maximal element in the `iterable`
 */
function maxBy(iterable, fn) {
    let maximalElement = iterable[0];
    for (let element of iterable) {
        if (fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;

}


// example generator function
generator = function* ()  {
   yield [3,4]
   yield [4,6]
}
maxBy(generator(), element => element[1])

When I run this in browser console, I get Uncaught TypeError: element is undefined error and I can't seem to spot where's the error in my code.

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

0

You cannot use iterable[0] to access the first element in a generator. You'll need to get the iterator and iterate it:

function maxBy(iterable, fn) {
    const iterator = iterable[Symbol.iterator]();
    const first = iterator.next();
    if (first.done) return;
    let maximalElement = first.value;
    for (let element of iterator) {
        if (fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;
}

Alternatively, just initialise maximalElement with undefined, this might happen anyway if the iterable is empty:

function maxBy(iterable, fn) {
    let maximalElement;
    for (let element of iterable) {
        if (maximalElement === undefined || fn(element) > fn(maximalElement)) {
            maximalElement = element;
        }
    }
    return maximalElement;

}
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