timoxley / functional-javascript-workshop

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

"Implement Map with Reduce"'s official solution has a bug in fn.call(). #157

Open gs20050101 opened 8 years ago

gs20050101 commented 8 years ago

Current official solution is as follows.

    module.exports = function arrayMap(arr, fn, thisArg) {
      return arr.reduce(function(acc, item, index, arr) {
        acc.push(fn.call(thisArg, item, index, arr))
        return acc
      }, [])
    }

I believe the correct answer is as follows. The reason is because fn is a user-specified function and it won't take the third (index) and fourth (arr) arguments.

    module.exports = function arrayMap(arr, fn, thisArg) {
      return arr.reduce(function(acc, item) {
        acc.push(fn.call(thisArg, item))
        return acc
      }, [])
    }