Implicit vs exlicit returns in reducer functionsContextAs explained in this discussion, a reduce function with an implicit return is VERY SLOW, because of the object spread operator/ Slow arr.reduce(
(acc, { id, value }) => ({
...acc,
[id]: value,
}),
{}
)Fast arr.reduce(
(acc, { id, value }) => {
acc[id] = value
return acc
},
{}
)Differences visualizedThe differences become more pronounced once the items length increases. At length 400 there is a significant divergence between the two approaches. Hence the advice to only use the slower variant up to 100-200 items. Fast and implicitBy using a small utility function you could keep doing implicit returns without the performance impact. const setProperty(obj, key, value) => {
obj[key] = value
return obj
}
list.reduce((out, item) => setProperty(out, item.key, item.value), {})Or alternatively, something like this: const reduceToObject = (list, extractor) => (
list.reduce((accum, item) => {
const [key, value] = extractor(item)
accum[key] = value
return accum
}, {})
)
reduceToObject(list, ({ key, value }) => [key, value])Migrated from gotchas |
Answered by
varl
Apr 16, 2021
Replies: 1 comment
|
See top post for the recommendations. |
0 replies
Answer selected by
varl
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

See top post for the recommendations.