킹의 개발일지
쏙쏙 들어오는 함수형 코딩 28일차 본문
28일차
<함수형 도구 체이닝>
왜 예제들은 항상 간단한 문제들을 가져올까 하는 생각이들 무렵, '함수형 도구 체이닝'파트에 도달했다.
함수형 도구 체이닝을 간단히 하면 '함수형 도구(map, fliter, ...)들을 조립해서 계산을 수행하는것' 이라고 볼 수 있는데, 대충 조립하면 이것만큼 가독성이 떨어지는게 없다. 한번보자
함수 기능을 먼저 설명하면, 구객들 중 우수고객(3개이상 구매)을 골라 그 구매들 중 가장 비싼 구매금액을 알아 내는함수다.
function biggestPurchasesBestCustomers(customers) {
var bestCustomers = filter(customers, (customer) => customer.purchases.length >= 3);
var biggestPurchases = map(bestCustomers, (customer) => {
return reduce(customer.purchases, {total: 0}, (biggestSoFar, purchase) => {
if (biggestSoFar.total > purchase.total) return bigestSoFar
else return purchase;
});
});
return biggestPurchases;
}
콜백에 콜백.. 여러개가 중첩되어 함수가 너무 커진다. 이를 리팩터링 해보자.
위 함수에서 가장 큰 구매값을 찾는 부분을 콜백으로 분리해보자.
function maxKey(arr, init, f) {
return reduce(arr, init, (biggestSoFar, elem) => {
if (f(biggestSoFar) > f(elem)) return biggestSoFar;
else elem;
}
}
이제 위에서 본 콜백 덩어리 함수에서 reduce 부분을 maxKey로 변경해보자.
function biggestPurchasesBestCustomers(customers) {
var bestCustomers = filter(customers, (customer) => customer.purchases.length >= 3);
var biggestPurchases = map(bestCustomers, (customer) => {
return maxKey(customer.purchases, {total: 0}, (purchase) => purchase.total);
});
return biggestPurchases;
}
더 간략해졌다. 하지만 코드에 중첩된 리턴 구문이 있는 콜백이 있다. 그래서 코드가 어떤 일을 하는지 알기 어렵다.
이를 해결하는 방법으로 2가지가 있는데, 이 중 하나만 설명해보겠다.
체인을 명확하게 만들기 2: 콜백에 이름 붙히기
function biggestPurchasesBestCustomers(customers) {
var bestCustomers = filter(customers, isGoodCustomer(customer));
var biggestPurchases = map(bestCustomers, getBiggestPurchase);
return biggestPurchases;
}
function isGoodCustomer(customer) {
return customer.purchase.length >= 3;
}
function getBiggestPurchase(customer) {
return maxKey(customer.purchases, {total: 0}, getPurchaseTotal);
}
function getPurchaseTotal(purchase) {
return purchase.total;
}
이렇게 콜백을 빼내고 이름을 붙히면 재사용할 수 있는 함수가 된다. 가독성, 재사용성까지 두마리 토끼를 잡았다고 볼 수 있다.
오늘 파트는 여러번 훑어봐야했다. 콜백이 중첩 되다보니 읽기가 여간 까다로운것이 아니었다... 실수하기 딱 좋아보였다. 심지어 예시 코드를 치면서도 몇번 실수가 생겼었다. 실제 프로젝트에 접목시켜 더 읽기 좋고 재사용하기 좋은 함수를 만들어보고 싶은 생각이 든다.
'독서 > 책너두 챌린지' 카테고리의 다른 글
| 쏙쏙 들어오는 함수형 코딩 30일차 (0) | 2023.09.11 |
|---|---|
| 쏙쏙 들어오는 함수형 코딩 29일차 (0) | 2023.09.09 |
| 쏙쏙 들어오는 함수형 코딩 (26 ~ 27일차) (0) | 2023.09.07 |
| 쏙쏙 들어오는 함수형 코딩 (16 ~ 20일차) (2) | 2023.09.07 |
| 쏙쏙 들어오는 함수형 코딩 (11 ~ 15일차) (0) | 2023.09.07 |