Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!