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

165
Visualizações
building and testing a custom reduce function

As the title says, I have to build a reduce function that is passed an array, a callback and an accumulator. The requirements for the reduce function are:

  1. should set accumulator to be the first item of the array if no accumulator is given
  2. should pass the second item of the array into the iterator first if no accumulator is given
  3. should pass every item of the array through the iterator if an accumulator is passed in
  4. should accept falsy values as a valid accumulator
  5. should pass in items from left to right through the iterator

I'm struggling with point #5. I have no idea how to approach the logic for it. Here's what I have so far:

function reduce(collection, callback, accumulator) {
if (Array.isArray(collection)) {

if (accumulator === undefined) {
    accumulator = collection[0];
    
    const [el1, ...rest] = collection;
    collection = [...rest];
  }

let result = accumulator; 
for (let element of collection) { 
    result = callback(result, element);
    }
   return result; 
} else { 
   for (const [key, value] of Object.entries(collection)) { 
       callback(); 
   } 
  } 
}

I have not included the code for #5, so when I run my reduce function against the tests that checks if all of the requirements have been met, I get the following:

  • should pass in items from left to right through the iterator: Expected [ 0, 1, 2, 3, 1, 2, 3, 4 ] to equal [ 1, 2, 3, 4 ]

And this is the specific test for #5 that it should pass, but isn't:

it('should pass in items from left to right through iterator', () => {
        const orderedResult = [];

        _.reduce([1, 2, 3, 4], (memo, item) => {
          orderedResult.push(item);
          return memo;
        }, 10);

        expect(orderedResult).toEqual([1, 2, 3, 4]);
      });

I don't understand what it's testing. Is it testing if accumulator is an empty array or an empty object? Completely confused. Please, any hints (or resources) you could give me to help me with this, with out divulging the answer, would be greatly appreciated.

about 4 years ago · Juan Pablo Isaza
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