4 ms·
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
by minitech 7y ago
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])
);