Reputation: 1678
I was wondering if it's safe to use an impure reducer in array.prototype.reduce
in javascript.
Example:
Let's say a I have following array:
[{ id: 0, value: 6 }, { id: 1, value: 25 }]
If I wanted to convert this to a map where the ID became the key and the value the value.
I have two options here: with a pure reducer and an impure one.
// pure option
const data = [{ id: 0, value: 6 }, { id: 1, value: 25 }];
const object = data.reduce((accum, { id, value }) =>
Object.assign({}, accum, { [id]: value }),
{}
);
const map = new Map(Object.entries(object));
// impure option
const data = [{ id: 0, value: 6 }, { id: 1, value: 25 }];
const map = data.reduce(
(accum, { id, value }) => accum.set(id, value),
new Map()
);
While the impure option is alot faster and has less boilerplate code, I am not sure if it's safe to or if it can give race conditions.
Upvotes: 1
Views: 202
Reputation: 21983
You're over-thinking this.
That's ok, a lot of us (myself included) wind up there. But ask yourself this question: from the perspective of the entity that is using your Map, can you tell the difference? Answer: no. In fact, a sufficiently smart compiler would turn the former into the latter. While I generally try to avoid being a human compiler while writing code, in this case the impure version is both shorter and clearer and faster.
Local state in Javascript is fine.
This is not to say that anything goes, I wouldn't mutate an external datastructure inside a reducer (or in any other function for that matter) but mutating one that doesn't "leak" outside the call to reduce and is instantiated solely for the purpose of being constructed that way is fine.
Upvotes: 1