자바스크립트 비동기 동시성 프로그래밍2

joDMSoluth·2020년 3월 14일
0

함수형프로그래밍

목록 보기
2/17

지연 평가 + 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);
profile
풀스택이 되고 싶은 주니어 웹 개발자입니다.

0개의 댓글