함수형 프로그래밍 스터디 2주차
2024. 2. 6. 15:04ㆍ카테고리 없음
728x90
반응형
요점
- 암묵적인 입력, 암묵적인 출력을 가지고 있는 함수는 액션이다.
- 계산은 암묵적인 입출력이 없어야한다.
- 전역변수는 암묵적 입출력이다.
- 암묵적 입력은 인자로 바꾸자.
- 암묵적 출력은 리턴값으로 바꾸자.
실습
Before
/*
1. map, filter, forEach 메소드를 순수 함수로 바꾸기
2. 비즈니스 로직과 유틸리티 함수를 분리하기
*/
//자회사에 납입금을 보내는 함수
function affiliatePayout(affiliates) {
//납입금 계산
const oweds = affiliates.map(e => {
return {
bank_code: e.bank_code,
owed: e.sales * e.commission
};
});
//송금여부 판단
const payoutList = oweds.filter(e => e.owed > 100);
//송금하기
payoutList.forEach(e => {
sendPayout(e.bank_code, e.owed);
});
}
function main(affiliates) {
affiliatePayout(affiliates);
}
After
/*
비즈니스 로직: makeBankCodeAndOwed, isOwedGreaterThan, sendPayout
유틸리티 함수: _map, _each, _filter
*/
//자회사에 납입금을 보내는 함수
function affiliatePayout(affiliates) {
//납입금 계산
const bankCodeAndOweds = _map(affiliates, makeBankCodeAndOwed);
//송금여부 판단
const payoutList = _filter(bankCodeAndOweds, isOwedGreaterThan);
//송금하기
_each(payoutList, sendPayout);
}
function makeBankCodeAndOwed(affiliate) {
return {
bank_code: affiliate.bank_code,
owed: calcOwed(affiliate.sales, affiliate.commission)
};
}
function calcOwed(sales, commission) { //비즈니스 로직
return sales * commission;
}
function isOwedGreaterThan(affiliates) { //비즈니스 로직
return affiliates.owed > 100;
}
function sendPayout(affiliate) { //비즈니스 로직
console.log(`bank code : ${affiliate.bank_code}, fee : ${affiliate.owed}`);
}
function _map(list, mapper) { //유틸리티 함수
const new_list = [];
_each(list, (val) => {
new_list.push(mapper(val));
})
return new_list;
}
function _each(list, iter) { //유틸리티 함수
for (let i = 0; i < list.length; i++) {
iter(list[i]);
}
return list;
}
function _filter(list, predi) { //유틸리티 함수
const new_list = [];
_each(list, (val) => {
if (predi(val)) new_list.push(val);
});
return new_list;
}
function main(affiliates) {
affiliatePayout(affiliates);
}
const affiliates = [ //데이터
{
bank_code: 1,
sales: 1,
commission: 1
},
{
bank_code: 2,
sales: 2,
commission: 500
}
];
/* 실행 */
main(affiliates);
728x90
반응형