-
-
Save webflo-dev/ea2b82014fda0ce60716cd2dbd86f8d0 to your computer and use it in GitHub Desktop.
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
/** 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