ํจ์ํ ๊ฐ์ ์น์ 7 ๋ด์ฉ ์ ๋ฆฌ - 3
(๊ฐ์๋ช : ํจ์ํ ํ๋ก๊ทธ๋๋ฐ๊ณผ JavaScript ES6+ ์ ์ธ๋ ๊ฐ์ฌ๋)
- L.flatten ํจ์: ๋์ ์ผ๋ก ํ๋ฒ์ ํผ์ณ์ ํ ๋์ค๋ฅผ ๊ฐ์ง ์ผ์ ํ ๋ฐฐ์ด๋ก ๋ณํํด์ฃผ๋ ์ดํฐ๋ ์ดํฐ๋ฅผ ๋ฆฌํดํ๋ ํจ์
- flatten ํจ์: ์ฆ์ ๋ชจ๋ ํ๊ฐํ๋ ํจ์
์ด๋ฐ ๊ฐ์ด ์์๋
[[1,2], 3, 4, [5,6], [7,8,9]]
๊ฐ์ ๋ค ํผ์ณ์ ํ๋์ ๋ฐฐ์ด๋ก ๋ง๋๋ ์ญํ ์ ํ๋ค.
[...[1,2], 3, 4, ...[5,6], ...[7,8,9]]
// [1,2,3,4,5,6,7,8,9]flatten์ ์ง์ฐํจ์
const isIterable = a => a && a[Symbol.iterator];
L.flatten = function *() {
for (const a of iter) {
if (isIterable(a)) {
// a์์ ์๋ ๊ฐ๋ค์ ๋ฝ์ ๋ชจ๋ yield
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.next());
log(it.next());
// ๋ค๋ฝ์
log([...it]);const flatten = pipe(L.flatten, takeAll);
log(flatten( [[1,2],3,4,[5,6],[7,8,9]] ));flatMap์ map๊ณผ flatten์ ๋์์ ํ๋ ํจ์
// flatMap์ ์ธ์์ ์ ๋ฌ๋ ํจ์๋ฅผ ์ด์ฉํด์ ๋ฐฐ์ด ์์์ ๊ฐ๋ค์ ๋ณํ๋ฅผ ์ค์ ์ฌ์ฉํ ์ ์์
// ์์ชฝ์ ์๋ ๋ฐฐ์ด ์์์ ๊ฐ ํ๋ํ๋ ํจ์ ์ ์ฉ
([[1,2], [3,4], [5,6,7], 8,9, [10]]).flatMap(a => a.map(a => a*a)));
// --> ๊ฒฐ๊ตญ map์ ํ๊ณ flatten์ ํ๊ฒ๊ณผ ๋์ผํ๊ฒ ๋์flatMap์ ์ง์ฐํจ์
L.flatMap = curry(pipe(L.map, L.flatten));์ฆ์ ํ๊ฐํ flatMap
const flatMap = pipe(L.flatMap, takeAll);
const flatMap = curry(pipe(L.map, L.flatten, takeAll));
const flatMap = curry(pipe(L.map, flatten)); // flatten์์ ๋ชจ๋ ํ๊ฐ๋ฅผ ์๋ฃํ flatMap์ ๋ง๋ฆflatMap(range, map(a => a+1, [1,2,3]));
...L.flatMap(L.range, map(a => a+1, [1,2,3]));
flatMap(L.range, map(a => a+1, [1,2,3]));// ์ฆ์ํ๊ฐ๋๋ flatMap ์ฌ์ฉ
// ์ดํฐ๋ ์ดํฐ๋ก ๋ง๋ ํ next๋ก ํ์ํ ๋๊น์ง๋ง ์ํ
var it = L.flatMap(L.range, map(a => a+1, [1,2,3]));
it.next();
it.next();
it.next();
// take๋ก ์์์ 3๊ฐ๋ง ๊บผ๋ด์ ๋ณด๊ฒ ๋ค
take(3, L.flatMap(L.range, map(a => a+1, [1,2,3])))