Skip to content

Instantly share code, notes, and snippets.

@syafdia
Created May 15, 2017 08:43
Show Gist options
  • Save syafdia/07750b66fd70f600c88f858df9472f40 to your computer and use it in GitHub Desktop.
Save syafdia/07750b66fd70f600c88f858df9472f40 to your computer and use it in GitHub Desktop.
// Utils
const data = [0, 1, 2, 3, 4, 5];
const reduce = (fn) => (a) => (b) => b.reduce(fn, a);
const compose = (fns) => (a) => fns.reduceRight((acc, fn) => fn(acc), a);
// Transducer
const mapping = (transformerFn) => (combinerFn) => (acc, v) => combinerFn(acc, transformerFn(v));
const filtering = (testFn) => (combinerFn) => (acc, v) => testFn(v) ? combinerFn(acc, v) : acc;
const dropping = (totDrop) => (combinerFn) => (acc, v) => --totDrop >= 0 ? acc : combinerFn(acc, v);
const taking = (totTake) => (combinerFn) => (acc, v) => --totTake >= 0 ? combinerFn(acc, v) : acc;
// Main Function
const mulTen = (v) => v * 10;
const gtTwo = (v) => v > 2;
const concat = (acc, v) => acc.concat(v);
const output = reduce(
compose([
filtering(gtTwo),
mapping(mulTen),
taking(2),
dropping(1),
])(concat)
)([])(data);
console.log(output); // 40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment