Skip to content

Instantly share code, notes, and snippets.

@jmaicaaan
Last active August 23, 2020 08:31
Show Gist options
  • Save jmaicaaan/2c33a5d840f0828629de487666ee3aab to your computer and use it in GitHub Desktop.
Save jmaicaaan/2c33a5d840f0828629de487666ee3aab 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) => {
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