Last active
January 14, 2021 17:54
-
-
Save kolharsam/b6e36d10537c13f748813918fab20fe0 to your computer and use it in GitHub Desktop.
Dabbling with Transducers in JS
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 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