Last active
June 19, 2019 14:20
-
-
Save SebastianHGonzalez/37f35a0f258457e04b00fca32000e34a to your computer and use it in GitHub Desktop.
JS Transducers
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 arrayReducer = (arr, elemnt) => arr.concat(elemnt) | |
arrayReducer.baseCase = [] | |
const stringReducer = (string, string2) => string + string2 | |
stringReducer.baseCase = "" | |
const functionReducer = (value, f) => f(value) | |
const mapTransducer = (f) => (reducer) => (acc, curr) => reducer(acc, f(curr)) | |
const filterTransducer = (f) => (reducer) => (acc, curr) => f(curr) ? reducer(acc, curr) : acc | |
const filterEvenTransducer = filterTransducer((n) => n % 2) | |
const mapIncTransducer = mapTransducer((n) => n + 1) | |
const filterShortTransducer = filterTransducer((s) => s.length < 3) | |
const mapToUpperCaseTransducer = mapTransducer((s) => s.toUpperCase()) | |
const compose = (...fs) => (arg) => fs.reduceRight(functionReducer, arg) | |
console.log( | |
'Composing transducers: filterEvenTransducer with mapIncTransducer into an arrayReducer', | |
[11, 22, 33, 44].reduce( | |
compose( | |
filterEvenTransducer, | |
mapIncTransducer | |
)(arrayReducer), | |
arrayReducer.baseCase | |
) | |
) | |
// [12, 34] | |
console.log( | |
'Composing transducers: filterShortTransducer with mapToUpperCaseTransducer into a stringReducer', | |
["fa", "fee", "fi", "foo", "fuuu"].reduce( | |
compose( | |
filterShortTransducer, | |
mapToUpperCaseTransducer | |
)(stringReducer), | |
stringReducer.baseCase | |
) | |
) | |
// FAFI | |
console.log( | |
'Composing transducers: filterShortTransducer with mapToUpperCaseTransducer into an arrayReducer', | |
["fa", "fee", "fi", "foo", "fuuu"].reduce( | |
compose( | |
filterShortTransducer, | |
mapToUpperCaseTransducer | |
)(arrayReducer), | |
arrayReducer.baseCase | |
) | |
) | |
// ["FA", "FI"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment