Last active
November 5, 2019 15:32
-
-
Save guillaumegarcia13/6a67b3060f6515bbdd5eeec1a88dd445 to your computer and use it in GitHub Desktop.
Reduce compilation (rewrite some classic collection methods using reduce)
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
/* From: https://medium.com/@hkairi/reduce-le-couteau-suisse-du-d%C3%A9veloppeur-javascript-8cf4b6f98304 | |
1. min() | |
2. max() | |
3. length() | |
4. map() | |
5. filter() | |
6. reverse() | |
7. unique() | |
8. take() | |
9. any() | |
10. every() | |
*/ | |
/* 1. min */ | |
const MinAetB = (x, y) => x < y ? x : y | |
const min = (collection) => collection.reduce(MinAetB, collection[0]); | |
/* 2. max */ | |
const MaxAetB = (a, b) => a > b ? a : b; | |
const max = (collection) => collection.reduce(MaxAetB, collection[0]); | |
/* 3. length */ | |
const length = (collection) => collection.reduce((count, _) => count + 1, 0); | |
/* 4. map */ | |
const map = | |
(fn, collection) => collection.reduce( | |
(acc, item) => acc.concat( fn(item) ), | |
[]); | |
/* 5. filter */ | |
const filter = | |
(fn, collection) => collection.reduce( | |
(acc, item) => fn(item) ? acc.concat(item) : acc, | |
[]); | |
/* 6. reverse */ | |
const reverse = | |
(collection) => collection.reduce( | |
(acc, item) => [item].concat(acc), | |
[]); | |
/* 7. unique */ | |
const unique = | |
(collection) => collection.reduce( | |
(acc, item) => { | |
if( collection.indexOf(item) === -1 ){ | |
return acc.concat(item); | |
} else { | |
return acc; | |
} | |
}, | |
[]); | |
/* 8. take */ | |
const take = | |
(nb, collection) => collection.reduce( | |
(acc, item) => { | |
if(nb > 0){ | |
nb--; | |
return acc.concat(item); | |
} else { | |
return acc; | |
} | |
}, | |
nb); | |
/* 9. any */ | |
const any = | |
(predicat, collection) => collection.reduce( | |
(acc, item) => predicat(item) || acc, | |
false); | |
/* 10. every */ | |
const every = | |
(predicat, collection) => collection.reduce( | |
(acc, item) => predicat(item) && acc, | |
true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment