Last active
August 23, 2020 08:31
-
-
Save jmaicaaan/2c33a5d840f0828629de487666ee3aab to your computer and use it in GitHub Desktop.
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 data = [ | |
1, | |
2, | |
3, | |
4, | |
5, | |
]; | |
/** | |
* | |
* This utility function is often available on various | |
* functional libraries (i.e ramdajs) | |
* `pipe` is the opposite of `compose` | |
*/ | |
const pipe = (...fns) => initialValue => fns.reduce((result, fn) => fn(result), initialValue); | |
const addBy1 = (x) => x + 1; | |
const multiplyBy2 = (x) => x * 2; | |
const getItemsBelow10 = (x) => x < 10; | |
const sum = (accumulator, currentValue) => accumulator += currentValue; | |
const mapReduce = mapperFn => combinerFn => (accumulator, currentValue) => { | |
return combinerFn(accumulator, mapperFn(currentValue)); | |
}; | |
const filterReduce = predicateFn => combinerFn => (accumulator, currentValue) => { | |
if (predicateFn(currentValue)) { | |
return combinerFn(accumulator, currentValue); | |
} | |
return accumulator; | |
}; | |
const combinerConcat = (accumulator, currentValue) => { | |
accumulator.push(currentValue); | |
return accumulator; | |
}; | |
const transducer = pipe( | |
mapReduce(addBy1), | |
mapReduce(multiplyBy2), | |
filterReduce(getItemsBelow10) | |
); | |
const res = data | |
.reduce(transducer(combinerConcat), []) | |
.reduce(sum, 0) | |
// 35 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment