News for hackers. Stuff that matters.
Re:How to use array reduce for more than just numbers by minitech on Sunday June 02, 2019 @11:49AM (#20076162)
It’s n^2 time, not space. Each property of the object gets copied each time around, and the number of properties being copied increases each time around.

It’s probably a good idea to start considering this kind of copying an antipattern. The good news is that the correct implementation doesn’t have to involve mutating any arguments, just a local with unambiguous ownership:

  const keyBy = (iterable, key) => {
      const map = new Map();

      for (const value of iterable) {
          map.set(key(value), value);
      }

      return map;
  };

  const peopleObj = keyBy(peopleArr, person => person.username);
If you have an array, you even get to keep using array methods, which everyone loves:

  const keyBy = (array, key) =>
      new Map(
          array.map(value => [key(value), value])
      );

There are no comments on this comment yet.