-
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 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
See top post for the recommendations. |
Beta Was this translation helpful? Give feedback.
See top post for the recommendations.