const map = (f, iter) => {
let res = [];
for (const p of iter) {
res.push(f(p));
// ์ด๋ค ๊ฐ์ ๋ฃ์์ง ๋ณด์กฐ ํจ์์ ์์
}
return res;
}
log(map(p => p.name, products));
let m = new Map();
m.set('a', 10);
m.set('b', 20);
log(new Map(map(([k, v]) => [k, v * 2], m)));
const filter = (f, iter) => {
let res = [];
for (const a of iter) {
if (f(a)) res.push(a);
// ์ด๋ค ์กฐ๊ฑด์ ์ค์ง ๋ณด์กฐ ํจ์์ ์์
}
return push;
};
-- ์์ ๊ฐ์ด ์ดํฐ๋ฌ๋ธ ํ๋กํ ์ฝ์ ๋ฐ๋ฅธ filter ํจ์๋ ๋ชจ๋ ๊ฒ๋ค์ filterํ ์ ์์
const reduce = (f, acc, iter) => {
if (!iter) {
iter = acc[Symbol.iterator]();
acc = iter.next().value;
}
for (const a of iter) {
acc = f(acc, a);
}
return acc;
};
log(
reduce(
add,
map(p => p.price,
filter(p => p.price < 20000, products))));
)
)
์ฝ๋๋ฅผ ๊ฐ์ผ๋ก ๋ค๋ฃจ์ด ํํ๋ ฅ ๋์ด๊ธฐ
const go = (...args) => reduce((a, f) => f(a), args);
go(
0,
a => a + 1,
a => a + 10,
a => a + 100,
log
);
// 111
go(
products,
products => filter(p => p.price < 20000, products,
products => map(p => p.price, products),
prices => reduce(add, prices),
log);
)
// ์ ์ค์ฒฉ๋ ์ฝ๋๋ฅผ ์ฝ๊ธฐ ์ฝ๋๋ก ๊ฐ์
go(
products,
filter(p => p.price < 20000),
map(p => p.price),
reduce(add),
log);
)
// curry๋ฅผ ํตํด ๋ณด๋ค ๊ฐ๊ฒฐํ๊ฒ ๊ฐ์ (filter, map, reduce์ curry์ ์ฉ)
const pipe = (...fs) => (a) => go(a, ...fs);
const f = pipe(
a => a + 1,
a => a + 10,
a => a + 100,
);
log(f(0));
// 111
const curry = f =>
(a, ..._) => _.length ? f(a, ..._) : (..._) => f(a, ..._);
// ํจ์๋ฅผ ๋ฐ์์ ํจ์๋ฅผ ๋ฆฌํดํ๋๋ฐ ํจ์๊ฐ ์คํ๋์์ ๋
// ์ธ์๊ฐ ๋๊ฐ ์ด์์ด๋ผ๋ฉด ๋ฐ์๋ ํจ์๋ฅผ ์ฆ์์คํํ๊ณ
// ํ๊ฐ๋ผ๋ฉด ํจ์๋ฅผ ๋ค์ ๋ฆฌํดํ ํ์ ์ดํ์ ๋ฐ์ ์ธ์๋ฅผ ํฉ์ณ์ ์คํํ๋ ํจ์
const mult = curry((a, b) => a*b);
log(mult(1)(3));
// 3
const mult3 = mult(3);
log(mult3(10));
log(mult3(5));
log(mult3(3));
// 30 15 9
ํจ์ ์กฐํฉ์ผ๋ก ํจ์ ๋ง๋ค๊ธฐ
const total_price = pipe(
map(p => p.price),
reduce(add));
const base_total_price = predi => pipe(
filter(predi),
total_price);
go(
products,
base_total_price(p => p.price < 20000),
log);
)