Last active
May 21, 2017 19:37
-
-
Save himynameisdave/babdb1b4eeb427d3a21f406d34e22523 to your computer and use it in GitHub Desktop.
Reduce your fears about .reduce() - twentySomethingsLongFullNames-reduce.js
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 isInTwenties = user => user.age >= 20 && user.age < 30; | |
const makeFullName = user => `${user.firstName} ${user.lastName}`; | |
const isAtLeastTenChars = fullName => fullName.length >= 10; | |
const twentySomethingsLongFullNames = users.reduce( | |
// The first arg that .reduce takes is the reducer function | |
// It has the signature: | |
// - `accumulator` - this is what you build up as you move through the array | |
// - `user` - this is the reference to the item in the array we are currently on | |
// - `index` - not used here, but you can get the index of the current place in the array you are | |
// - `array` - not used here, but this refers to the original array if you need a ref to it | |
(accumulator, user) => { | |
const fullName = makeFullName(user); | |
if (isInTwenties(user) && isAtLeastTenChars(fullName)) accumulator.push(fullName); | |
return accumulator | |
}, | |
// The second argument (optional) is the initial value | |
// This will be the value of `accumulator` in the first iteration of `.reduce` | |
[] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment