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

121
Visualizações
Reduce Pollyfill

I was playing around with this array reduce polyfill and I'm just confused why is he/she using apply. I know that apply adds this context in the execution. But I don't know why we need it here, I just tried without it, and it works fine too.

Array.prototype.reduce = function (cb, initialValue) {
  console.log('inside my reducer');
  if (!cb || typeof cb !== 'function') throw TypeError();
  var len = this.length;
  var i = 0;
  console.log('this', this);
  if (typeof initialValue === 'undefined' || initialValue === null) {
    initialValue = this[0];
    ++i;
  }

  for (; i < len; i++) {
    initialValue = cb.apply(this, [initialValue, this[i], i, this]);

    //comment the line above and uncomment this line and it will work fine
    //initialValue = cb(initialValue, this[i]); 
    
  }

  return initialValue;
};
[1, 2, 1, 1].reduce((a, b) => a + b, 0); => 5

So, I'm a little confused, if anyone could share some insights it'll be apreciated. Thanks!

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

0

Wherever you got that polyfill, it's incorrect, in a couple of ways but in particular that initialValue = cb.apply(this, [initialValue, this[i], i, this]); should be using undefined, not this, in the first argument. reduce always calls its callback with this set to undefined (it'll end up being the global object if the callback is in loose mode rather than strict mode). So either initialValue = cb.apply(undefined, [initialValue, this[i], i, this]); or (more directly) initialValue = cb(initialValue, this[i], i, this);

Separately, it makes no sense to use apply and create an array to provide to it rather than using call with the discrete values it already has. Also, continuing to use something called initialValue for the accumulator is, at best, misleading. And it doesn't handle it correctly if you do [].reduce(x => x) (it should throw an error, not return undefined [note no seed value]).

So basically, I wouldn't put much faith in that polyfill, since it's providing the array, rather than undefined, as this during callbacks.

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