Created
August 22, 2020 18:29
-
-
Save jmaicaaan/7f217cf3f7d638596d7c503a4083f491 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) => { | |
const result = mapperFn(currentValue); | |
return combinerFn(accumulator, result); | |
}; | |
const filterReduce = predicateFn => combinerFn => (accumulator, currentValue) => { | |
if (predicateFn(currentValue)) { | |
return combinerFn(accumulator, currentValue); | |
} | |
return accumulator; | |
}; | |
const combinerConcat = (accumulator, currentValue) => [...accumulator, currentValue]; | |
const res = data | |
.reduce(mapReduce(addBy1)(combinerConcat), []) | |
.reduce(mapReduce(multiplyBy2)(combinerConcat), []) | |
.reduce(filterReduce(getItemsBelow10)(combinerConcat), []) | |
.reduce(sum, 0) | |
res | |
// 18 | |
const transducer = pipe( | |
mapReduce(addBy1), | |
mapReduce(multiplyBy2), | |
filterReduce(getItemsBelow10), | |
); | |
const res1 = data | |
.reduce( | |
transducer(sum), | |
0 | |
) | |
res1 | |
// 35 expected 18 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because of the way transduction works, it sort of "reverses" the order of a composition (or pipe)... so if you change your
pipe(..)
call to this:You get
18
the way you're hoping.IOW, with transduction, a
compose(..)
is listed left-to-right (not right-to-left) and apipe(..)
is right-to-left (not left-to-right). So, probably should stick withcompose(..)
.