Last active
November 28, 2018 20:07
-
-
Save inkdeep/99545166f4d96679ad7a489ba22258f9 to your computer and use it in GitHub Desktop.
modification of examples from: https://medium.com/@roman01la/understanding-transducers-in-javascript-3500d3bd9624
This file contains 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
/* | |
arrays | |
*/ | |
const _set = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; | |
const _set2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
/* | |
predicates | |
*/ | |
const isEven = x => x % 2 === 0; | |
const addOne = x => x + 1; | |
const squared = x => x * x; | |
/* | |
reducing functions | |
*/ | |
const mapReducer = f => (result, input) => { | |
result.push(f(input)); | |
return result; | |
}; | |
const filterReducer = predicate => (result, input) => { | |
if (predicate(input)) { | |
result.push(input); | |
} | |
return result; | |
}; | |
console.log("add one", _set.reduce(mapReducer(addOne), [])); | |
console.log("squared", _set.reduce(mapReducer(squared), [])); | |
console.log("is even", _set2.reduce(filterReducer(isEven), [])); | |
/* | |
composable reducers | |
*/ | |
const mapping = f => reducing => (result, input) => reducing(result, f(input)); | |
const filtering = predicate => reducing => (result, input) => | |
predicate(input) ? reducing(result, input) : result; | |
const accumulator = (xs, x) => { | |
xs.push(x); | |
return xs; | |
}; | |
const transduce = (transformationReducers, reducing, initial, input) => | |
input.reduce(transformationReducers(reducing), initial); | |
// simple compose helper - ramda `compose` lets you compose n* number of reducers, instead of just the three this one does | |
const compose = (f, g, h) => x => f(g(h(x))); | |
const addToEvenAndSquare = compose( | |
filtering(isEven), | |
mapping(addOne), | |
mapping(squared) | |
); | |
console.log( | |
"add one, is even", | |
_set | |
.reduce(mapping(addOne)(accumulator), []) | |
.reduce(filtering(isEven)(accumulator), []) | |
); | |
console.log( | |
"add one, is even (reducer composition as reducer)", | |
_set.reduce(mapping(addOne)(filtering(isEven)(accumulator)), []) | |
); | |
console.log( | |
"addToEvenAndSquare using transduce helper function", | |
transduce(addToEvenAndSquare, accumulator, [], _set) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment