Skip to content

Instantly share code, notes, and snippets.

@kolharsam
Last active January 14, 2021 17:54
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 kolharsam/b6e36d10537c13f748813918fab20fe0 to your computer and use it in GitHub Desktop.
Save kolharsam/b6e36d10537c13f748813918fab20fe0 to your computer and use it in GitHub Desktop.
Dabbling with Transducers in JS
const list = [1,2,3,4,5,6,7,8,9];
const inc = x => x + 1;
const isOdd = x => x % 2 !== 0;
console.log(list.map(inc));
console.log(list.filter(isOdd))
console.log(list.map(inc).filter(isOdd))
console.log(list.reduce((acc, val) => {
if (isOdd(inc(val))) {
return [...acc, inc(val)];
}
return acc;
}, []));
const comp = (...fns) => x =>
fns.reduceRight((prevAnswer, fn) => fn(prevAnswer), x);
const compT = (...fns) => (acc, val) => {
const r = fns.reduceRight((prevAnswer, fn) => {
return prevAnswer.reduce((a,v) => {
return fn(a, v);
}, []);
}, [val]);
if (!r) {
return acc;
}
if (Array.isArray(r)) {
return [...acc, ...r];
}
return [...acc, r];
};
const compMapFilter = comp(isOdd, inc);
const cmpRes = list.reduce((acc, val) => {
const res = compMapFilter(val);
if (res) {
return [...acc, val];
};
return acc;
}, []);
console.log(cmpRes)
const mapT = mappingFn => (acc, val) => {
return [...acc, mappingFn(val)];
};
const filterT = predicate => (acc, val) => {
if (predicate(val)) {
return [...acc, val];
}
return acc;
};
const compTs = compT(filterT(isOdd), mapT(inc));
console.log(list.reduce(mapT(inc), []));
console.log(list.reduce(filterT(isOdd), []));
console.log(list.reduce(compTs, []));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment