Created
July 9, 2019 22:27
-
-
Save agm1984/84c5438f060dc341a84a08f18214120d to your computer and use it in GitHub Desktop.
How Array.prototype.reduce works
This file contains 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 poop = ['one', 'two', 'three', 'four', 'five'] | |
// I always use `acc` and `item` by default | |
// acc is the thing being accumulated | |
// item is each item in `poop` | |
// basic idea: this will do nothing, | |
// add some console.logs in here and study the behaviour | |
// look at the example below that uses `i` and add it here with console.log | |
const ultraBasic = poop.reduce((acc, item) => { | |
acc.push(item) | |
return acc | |
}, []) | |
console.log('ultraBasic', ultraBasic) | |
// now study this one | |
const accumulateObj = poop.reduce((acc, item) => { | |
acc[item] = item | |
return acc | |
}, {}) | |
console.log('accumulateObj', accumulateObj) | |
// now study this one | |
const accumulateNum = poop.reduce((acc, item, i) => { | |
acc += i | |
return acc | |
}, 0) | |
console.log('accumulateNum', accumulateNum) | |
// now study this next-level swiss-army knife | |
const accumulateSavageUnit = poop.reduce((acc, item) => { | |
if (item.length < 4) acc.short.push(item) | |
if (item.length >= 4) acc.long.push(item) | |
return acc | |
}, { short: [], long: [] }) | |
console.log('accumulateSavageUnit', accumulateSavageUnit) | |
// key mentions: | |
// 1) notice how the second param of reduce is the initial state | |
// 2) notice how it looks like map except the accumulator comes in | |
// every time along with the item | |
// 3) notice how the accumulator is returned every iteration | |
// 4) notice how it ends with returning the completed accumulation-product | |
// 5) notice how you can imagine a million ways to use this type of process |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment