코드를 값으로 다루어 표현력 높이기
go, pipe
const go = (...args) => {
reduce((a, f) => f(a), args);
};
go([
0,
a => a + 1,
a => a + 10,
a => a + 100,
console.log]);
go(
add(0, 1),
a => a + 10,
a => a + 100),
log);
const pipe = (f, ...fs) => (...as) => go(f(...as), ...fs);
const f = pipe(
a => a + 1,
a => a + 10,
a => a + 100);
console.log(f(0));
const f = pipe(
(a, b) => a + b,
a => a + 10,
a => a + 100);
console.log(f(0, 1));
go를 이용한 좋은 코드
go(
products,
products => filter(p => p.price < 20000, products),
products => map(p => p.price, products),
prices => reduce(add, prices),
console.log);
go + curry를 이용하여 더 좋은 코드
const currry = f =>
(a, ..._) =>
_.length
? f(a, ..._)
: (..._) => f(a, ..._);
const mult = curry((a, b) => a * b);
console.log(mult(3)(2));
const mult3 = mult(3);
console.log(mult3(10));
console.log(mult3(5));
console.log(mult3(3));
const _map = curry(map);
const _filter = curry(filter);
const _reduce = curry(reduce);
go(
products,
filter(p => p.price < 20000),
map(p => p.price),
reduce(add),
console.log);
pipe를 이용하여 중복 제거
const total_price = pipe(
map(p => p.price),
reduce(add));
go(
products,
filter(p => p.price < 20000),
map(p => p.price),
reduce(add),
console.log);
go(
products,
filter(p => p.price < 20000),
total_price,
console.log);
const base_total_price = predi => pipe(
filter(predi),
total_price);
go(
products,
base_total_price(p => p.price < 20000),
console.log);