const products = [
{ name: '반팔티', price: 15000, quantity: 1, is_selected: true },
{ name: '긴팔티', price: 20000, quantity: 2, is_selected: false },
{ name: '핸드폰케이스', price: 15000, quantity: 3, is_selected: true },
{ name: '후드티', price: 30000, quantity: 4, is_selected: false },
{ name: '바지', price: 25000, quantity: 5, is_selected: false }
]
<aside> 💡 우리가 작성한 iterable 함수들을 사용하자
</aside>
const add = (a, b) => a + b
const sum = curry((f, iter) => go(iter, map(f), reduce(add)))
const total_quantity = pipe(
map((el) => el.quantity),
reduce(add)
)
log(total_quantity(products)) // 15
const total_price = pipe(
map((el) => el.price * el.quantity),
reduce(add)
)
log(total_price(products)) // 345000
<aside> 💡 우리는 여기에서 어떻게 더 간소화할 수 있을까?
</aside>
<aside> 💡 동일한 부분을 찾아내고 좀 더 고차원적인 추상화를 한다는 생각을 항상 가지고 있자!!
</aside>
const add = (a, b) => a + b
// map의 조건은 매개변수로 맡기고 추상화에 집중한다
const sum = curry((f, iter) => go(iter, map(f), reduce(add)))
const total_quantity = sum((el) => el.quantity)
log(total_quantity(products)) // 15
const total_price = sum((el) => el.price * el.quantity)
log(total_price(products)) // 345000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>HTML 출력해보기 - 장바구니</title>
<script src="./forHtml/fx.js"></script>
</head>
<body>
<div id="cart"></div>
<script>
const products = [
{ name: '반팔티', price: 15000, quantity: 1, is_selected: true },
{ name: '긴팔티', price: 20000, quantity: 2, is_selected: true },
{ name: '핸드폰케이스', price: 15000, quantity: 3, is_selected: true },
{ name: '후드티', price: 30000, quantity: 4, is_selected: false },
{ name: '바지', price: 25000, quantity: 5, is_selected: false }
]
const add = (a, b) => a + b
const sum = curry((f, iter) => go(iter, map(f), reduce(add)))
const total_quantity = sum((el) => el.quantity)
log(total_quantity(products))
const total_price = sum((el) => el.price * el.quantity)
log(total_price(products))
document.querySelector('#cart').innerHTML = `
<table>
<tr>
<th></th>
<th>상품 이름</th>
<th>가격</th>
<th>수량</th>
<th>총 가격</th>
</tr>
${go(
products,
sum(
(p) => `
<tr>
<td><input type="checkbox" ${p.is_selected ? 'checked' : ''}></td>
<td>${p.name}</td>
<td>${p.price}</td>
<td><input type="number" value="${p.quantity}"></td>
<td>${p.price * p.quantity}</td>
</tr>
`
)
)}
<tr>
<td colspan="3">합계</td>
<td>${total_quantity(filter((p) => p.is_selected)(products))}</td>
<td>${total_price(filter((p) => p.is_selected, products))}</td>
</tr>
</table>
`
</script>
</body>
</html>