지연 평가 + Promise - L.map, map, take
const go1 = (a, f) => a instanceof Promise ? a.then(f) : f(a);
L.map = curry(function *(f, iter) {
for (const a of iter) {
yield go1(a, f);
}
});
const take = curry((l, iter) => {
let res = [];
iter = iter[Symbol.iterator]();
return function recur() {
let cur;
while (!(cur = iter.next()).done) {
const a = cur.value;
if (a instanceof Promise)
return a.then(a => (
res.push(a), res).length ===l ? res : recur());
res.push(a);
if (res.length === l) return res;
}
return res;
} ();
})
go(Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]
L.map(a => Promise.resolve(a + 10)),
take(2),
console.log);
Kleisli Composition - L.filter, filter, nop, take
const nop = Symbol('nop');
L.filter = curry(function *(a, iter) {
for (const a of iter) {
const b = go1(a, f);'
if (b instanceof Promise)
yield b.then(b => b ? a : Promise.reject(nop))
else if (b) yield a;
}
}
go([1, 2, 3, 4, 5, 6],
L.map(a => Promise.resolve(a * a)),
L.filter(a => {
console.log(a);
return a % 2
}),
take(2),
console.log);