Last active
September 14, 2019 07:01
-
-
Save dgowrie/b88e4c68476507e4c242ab9102292713 to your computer and use it in GitHub Desktop.
Map, Reduce, Filter, chained usage - web dev interview, discussion
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 animals = ['cat', 'dog', 'fish']; | |
const lengths = animals.map(animal => animal.length); | |
console.log(lengths); | |
const reducer = (acc, word) => acc + word.length; | |
const letterCount = animals.reduce(reducer, 0); | |
console.log(letterCount); | |
const hasThree = word => word.length === 3; | |
const threeLetterAnimals = animals.filter(hasThree); | |
console.log(threeLetterAnimals); | |
// all together now | |
// initial implementation | |
// can abstract pure functions for more reuse and clarity | |
// e.g. like we already did with `hasThree` earlier, reuse here | |
const studum = (acc, item) => { | |
const word = item.charAt(0).toUpperCase() + item.slice(1); | |
return acc + word; | |
}; | |
const animalsStudCaps = animals.filter(hasThree) | |
.reduce(studum, ''); | |
console.log(animalsStudCaps); | |
// with abstrations to pure functions | |
const capitalize = word => word.charAt(0).toUpperCase() + word.slice(1); | |
const mergeWords = (words, word) => words + word; | |
const animalsThreeCaps = animals.filter(hasThree) | |
.map(capitalize) | |
.reduce(mergeWords, ''); | |
console.log('purified', animalsThreeCaps); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment