Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda