Skip to content

Instantly share code, notes, and snippets.

@jmaicaaan
Created August 22, 2020 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmaicaaan/7f217cf3f7d638596d7c503a4083f491 to your computer and use it in GitHub Desktop.
Save jmaicaaan/7f217cf3f7d638596d7c503a4083f491 to your computer and use it in GitHub Desktop.
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
@getify
Copy link

getify commented Aug 22, 2020

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:

const transducer = pipe(
  filterReduce(getItemsBelow10),
  mapReduce(multiplyBy2),
  mapReduce(addBy1),
);

You get 18 the way you're hoping.

IOW, with transduction, a compose(..) is listed left-to-right (not right-to-left) and a pipe(..) is right-to-left (not left-to-right). So, probably should stick with compose(..).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment