Exercise [7] - Basic Recursion
joaocferreira opened this issue · 1 comments
joaocferreira commented
function reduce(arr, fn, initial) {
if (arr[0]) {
initial = fn(initial, arr.splice(0, 1));
return reduce(arr, fn, initial);
} else {
return initial;
}
};
I did this solution that seems to do what is expected but fails on the tests. Can anyone point what i may be missing?
orthotypos commented
@joaocferreira .splice()
method will return an array. But in general, splice is not really good method for "functional-javascript-workshop" (it mutates the original array).
Try using .slice()
instead, like:
function reduce(arr, fn, initial) {
if (arr[0]) {
initial = fn(initial, arr[0]);
return reduce(arr.slice(1), fn, initial);
} else {
return initial;
}
};
This will pass you a test, but technically solution is not 100% complete, as callback fn
is not satisfying requirement:
fn: Function to use as the reduction step. Like regular Array#reduce, this function must be passed previousValue, currentValue, index and the array we're iterating over.