I am actually having an issue, more with the instructions for this homework problem which are as follows:
Reduces collection to a value which is the accumulated result of running each element in collection through iteratee, where each successive invocation is supplied the return value of the previous. If accumulator is not provided the first element of collection is used as the initial value. If a start parameter is not provided, then set the start value as the zeroth index.
here is the breakdown of what is supposed to happen:
// reduce([1,2], function(stored,current) {
// return stored + current;
// }); → 3
// reduce([1,2], function(stored,current) {
// return stored + current;
// },1); → 4
if i'm reading the instructions correctly, the start parameter is the initial value to start accumulating to, no? and if no start parameter is supplied in the call to the function, that the value at index 0 will be the start value. Only problem is when that value is grabbed in cases where no start parameter is supplied, the first val is accumulated twice, which returns a result that is not expected.
as of now i've looked into the reduce method and different ways of starting at different indices. it's looking like if no start value is provided, that I would need to set the initial value to array[0] and then array.slice(1) and reduce from there, however, i'm not really sure that's what the assignment says to do.
I'm not quite understanding the difference between if an accumulator is not provided and if a start parameter is not provided. If an accumulator isn't provided, wouldn't the initial value be the first value in the input array, and the starting index be 1? so to not add/subtract the first value twice?
here's my code:
function reduce(array, callback, start) {
return array.reduce((acc, val, start) => {
//if start value not provided, start value is index 0
return callback(acc, val) }, start || array[0])
}
here are results.
//start provided as -1, result correct
var difference = function(tally, item) {return tally - item; };
var total = reduce([1, 2, 3], difference, -1); // expected -> -7 got -7
//start provded as 2, result correct
var add = function(tally, item) {return tally + item; };
var total = reduce([1, 2, 3], add, 2); // expected -> 8 got 8
//start not provided, first index used as start, as per instructions
//therefore first index is added twice, giving wrong answer
var add = function(tally, item) {return tally + item; };
var total = reduce([1, 2, 3], add); // expected -> 6 got 7
//start not provided, first index used as start, as per instructions
//therefore first index is subtracted twice, giving wrong answer
var difference = function(tally, item) { return tally - item; };
var total = reduce([1, 2, 3], difference); // -> expected -4 got -5