총 수량, 총 가격


PREV: 테스트 대상 원천 데이터

Step 1: 총 수량, 총 가격 구하기

const total_quantity = items => go(
    items,//인자값으로 받은 값을 그대로 반환(1)
    map(p => p.quantity),//리스트를 순회하며 각각의 객체에서 수량(p.quantity)을 꺼내어 값들을 배열로 만들어 전달(2)
    reduce((a, b) => a + b),// 인자값으로 받은 배열 파라미터를 덧셈으로 축약(3)
    );

const total_price = items => go(
    items,
    map(p => p.quantity * p.price),
    reduce((a, b) => a + b),
    );
log(total_price(books)); // 920000
log(total_quantity(books)); //22

Step 2: go → pipe로 리팩토링

const total_quantity = pipe(
    map(p => p.quantity),
    reduce((a, b) => a + b),
    );
const total_price = pipe(
    map(p => p.quantity * p.price),
    reduce((a, b) => a + b),
    );
log(total_price(books));
log(total_quantity(books));

Step 3: reduce의 인자값(a,b)⇒a+b 모듈화

const add = (a, b) => a + b;
const total_quantity = pipe(
    map(p => p.quantity),
    reduce(add),
    );
const total_price = pipe(
    map(p => p.quantity * p.price),
    reduce(add),
    );
log(total_price(books));
log(total_quantity(books));

Step 4: map, reduce 함수인자 모듈화

const add = (a, b) => a + b;
const sum = (f, iter) => go(
    iter,
    map(f),
    reduce(add));

const total_quantity = items => sum(p => p.quantity, items);
const total_price = items => sum(p=> p.quantity * p.price, items);

log(total_quantity(books));
log(total_price(books));

Step 5: Currying 함수 적용