timoxley / functional-javascript-workshop

A functional javascript workshop. No libraries required (i.e. no underscore), just ES5.
2.06k stars 441 forks source link

Exercise [7] - Basic Recursion #172

Open joaocferreira opened 7 years ago

joaocferreira commented 7 years ago
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 7 years ago

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