Currently, I am tackling a code challenge in JavaScript that requires me to develop a function called reduce. This function is responsible for reducing a collection to a value by applying a specific operation on each item in the collection over which it iterates. The necessary parameters for this function include the array, callback, and start. If the start parameter is not provided, it defaults to zero.
At present, my implementation looks like this:
function reduce(array, callback, start) {
if(typeof start === 'number'){
var initVal = start;
} else {
var initVal = 0;
}
return array.reduce(callback, initVal);
}
I have a set of tests prepared to evaluate my function, and it appears to be failing only one test that involves a callback function for subtracting values. The specific test causing failure is as follows:
var difference = function(tally, item) {return tally - item; };
var total = reduce([1, 2, 3], difference);
expect(total).to.equal(-4);
I would greatly appreciate any guidance or insights to help resolve this issue.
Update: Here is the revised working solution:
function reduce(array, callback, start) {
if( typeof start === 'undefined' ){
return array.reduce(callback);
} else {
return array.reduce(callback, start);
}
}