Last active
June 24, 2021 14:41
-
-
Save MauricioRobayo/2716c78ea1f9cefb3463ee82a35f728e to your computer and use it in GitHub Desktop.
All code using array.reduce should be rewritten without array.reduce so it's readable by humans https://twitter.com/jaffathecake/status/1213408744362692608 #gogofast
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object transformations should not use reduce. | |
Creating an object once, then passing the same object back through reduce is using reduce for decoration only. The only part of reduce it's using is the looping. | |
The applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Good | |
arr.reduce((total, item) => total + item); | |
// reduce used only as decoration | |
const obj = arr.reduce((obj, item) => { | |
obj[item] = null; | |
return obj; | |
}, {}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const obj = Object.fromEntries( | |
arr.map(item => [item, null]), | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const obj = {}; | |
for (const item of arr) obj[item] = null; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment