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:
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:
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.