[JavaScript] 지연성을 위한 ES6+ 함수형 프로그래밍 - 2

Hyuk·2023년 2월 18일
0

지연 평가를 하는 함수의 종류이다.

take

const take = (l, iter) => {
  let res = [];
  for (const a of iter) {
    res.push(a);
    if (res.length === l) return res
  }
  return res
}

console.log(take(5, range(100)))

L.map

const L = {};
L.map = function *(f, iter) {
	for (const a of iter) {
    	yield f(a)
    }
}

let it = L.map(a => a + 10, [1, 2, 3])

L.filter

const L = {};
L.filter = function *(f, iter) {
	for (const a of iter) {
    	if (f(a)) yield a
    }
}

let it = L.filter(a => a + 10, [1, 2, 3])

L.flatten

const L = {};

const isIterable = a => a && a[Symbol.iterator];

L.flatten = function *(iter) {
	for (const a of iter) {
    	if(isIterable(a)) {
        	for (const b of a) yield b;
        }
      	else yield a;
    }
}
profile
프론트엔드 개발자

0개의 댓글