loading...

Discussion on: Understanding Array reduce by building it from scratch

Collapse
kaul profile image
Keshav Kaul

Thanks for this simple article on reduce! I have a suggestion for changing the map method to a more performant version. Would love to see an article on rxjs's scan method!

The performance of this map is n2 because we are returning a new copied array inside the reducer method. Isn't this unnecessary immutability? Because we control the initial empty array state, we could mutate this array inside the reducer and still benefit from mutability for the caller of the map method.

Instead of this

Array.prototype.map = function (callback) {
  return this.reduce(
    (result, item, i, source) =>
      [...result, callback(item, i, source)],
    []
  );
}

We could do this -

Array.prototype.map = function (callback) {
  return this.reduce(
    (result, item, i, source) =>
      {
        result.push(callback(item, i, source))
        return result
      },
    []
  );
}