Created
April 12, 2020 17:44
-
-
Save Caballerog/79d1cd60afb94d91868a2ab7ce62a41e to your computer and use it in GitHub Desktop.
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
/** Operators */ | |
const map = (mapper) => (reducer) => (acc, val) => reducer(acc, mapper(val)); | |
const filter = (predicate) => (reducer) => (acc, val) => | |
predicate(val) ? reducer(acc, val) : acc; | |
const some = (predicate) => (_) => (acc, val) => | |
acc !== true ? predicate(val) : true; | |
/** */ | |
const pipe = (...fns) => | |
fns.reduce((reducer, nextReducer) => (...args) => | |
reducer(nextReducer(...args)), | |
); | |
const arrayOf = (acc, val) => (acc.push(val), acc); // push to Array | |
const inmutableArrayOf = (acc, val) => [...acc, val]; // push to Array | |
const transducer = (...fns) => (iterable) => { | |
const transform = pipe(...fns)(inmutableArrayOf); | |
return Array.from(iterable).reduce(transform, []); | |
}; | |
/* Example */ | |
const add1 = (x) => x + 1; | |
const greater2 = (x) => x > 2; | |
const numbers = [1, 2, 3]; | |
const result = transducer(map(add1), filter(greater2))(numbers); | |
console.log(result); // [3, 4] | |
const result2 = transducer(filter(greater2))(numbers); | |
console.log(result2); // [ 3 ] | |
const result3 = transducer( | |
map(add1), | |
some((x) => x > 5), | |
)(numbers); | |
console.log(result3); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment