이터러블 중심 프로그래밍에서의 지연평가 (Lazy Evaluation)
- 제때 계산법
- 느긋한 계산법
- 제너레이터/이터레이터 프로토콜을 기반으로 구현
range
const range = l => { let i = -1; let res = []; while (++i < l) { res.push(i); } return res; };
take
const take = (l, iter) => { let res = []; for (const a of iter) { res.push(a); if (res.length == l) return res; } return res; }
L.map
L.map = function *(f, iter) { for (const a of iter) yield f(a); }; var it = L.map(a => a + 10, [1,2,3]); console.log(it.next()); //11 console.log(it.next()); //12 console.log(it.next()); //13
L.filter
L.filter = function *(f, iter) { for (const a of iter) if(f(a)) yield a; }; var it = L.filter(a => a % 2, [1,2,3]); console.log(it.next()); //1 console.log(it.next()); //3 console.log(it.next()); //undefined
map, filter 계열 함수들이 가지는 결합 법칙
- 사용하는 데이터가 무엇이든지
- 사용하는 보조 함수가 순수 함수라면 무엇이든지
- 아래와 같이 결합한담녀 둘 다 결과가 같다.
[[mapping, mapping]], [filtering,filtering], [mapping,mapping]]
=
[[mapping,filtering,mapping], [mapping,filtering, mapping]]
queryStr 함수 만들기
const join = curry((sep = ',', iter)=> reduce((a,b) => `${a}${sep}${b}`, iter)); const queryStr = pipe( Object.entries, L.map(([k,v]) => `${k}=${v}`), function(a) { console.log(a); return a; }, reduce((a,b) => `${a}&${b}`) ); log(queryStr({limit: 10, offset: 10, type: 'notice'})); function *a() { yield 10; yield 11; yield 12; yield 13; } log(join('-', a()));
const users = [ {age: 32}, {age: 25}, {age: 27}, {age: 31}, {age: 50}, {age: 21}, ]; const find = curry((f, iter) => go( iter, L.filter(f), take(1), ([a] => a) ); console.log(find(u => u.age < 30)(users));
: array 들을 하나의 array로 변형해준다.
log([...[1,2],3,4,...[5,6],...[7,8,9]]); 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; } }; var it = L.flatten([[1,2], 3, 4, [5,6], [7,8,9]]); log([...it]);
: map + flatten
L.flatMap = curry(pipe(L.map, L.flatten)); const flatMap = curry(pipe(L.map, flatten)); var it = L.flatMap(a => a, [[1,2], [3,4], [5,6,7]]); log([...it]); log(flatMap(a => a, [[1,2], [3,4], [5,6,7])); log(map(range,[1,2,3]));
내장함수 import : https://fxts.dev/