일급 함수

jake·2021년 8월 6일
0

JavaScript문법

목록 보기
13/21
post-thumbnail

일급함수는 함수를 일반적인 값처럼 취급하다는 것

  • 인자를 함수로 넘겨주는 기법 사용
function ul(child:string): string {
    return `<ul>${child}</ul>`;    
}
function ol(child:string): string {
    return `<ol>${child}</ol>`;    
}
function makeLI(
    container:(child:string) => string, // 함수를 인자로 넘겨줌
    contents:string[]
    ) : string {
    const liList = [];
    for (const content of contents) {
        liList.push(`<li>${content}</li>`)
    }
    return container(liList.join(''));    
}
const htmlUL = makeLI(ul, ['월','화','수','목','금','토','일',]);
const htmlOL = makeLI(ol,['봄','여름','가을','겨울']);
console.log(htmlUL);
console.log(htmlOL);
  • 반환값으로 함수인 경우
    (변수에 넣을 수 있다는 장점이 생기면서 표현력이 극대화 된다)
function salePrice(discountRate, price) {
    return price - (price * (discountRate * 0.01));
} 
console.log('여름 세일 - ' + salePrice(30, 567000)); // 1번
console.log('겨울 세일 - ' + salePrice(10, 567000));
function discountPrice(discountRate) {
    return function(price){
        return price - (price * (discountRate * 0.01));
    }
}
console.log('여름 세일 - ' + salePrice(30)(567000)); // 2번
console.log('겨울 세일 - ' + salePrice(10)(567000));
let summerPirce = discountPrice(30);
let winterPirce = discountPrice(10);
console.log('여름 세일 - ' + summerPirce(567000)); // 3번
console.log('겨울 세일 - ' + winterPirce(567000));

이코드에서 '여름세일', '겨울세일'을 지우면 3번째 것이 직관적으로 어떤것을 표현하는지 한눈에

profile
열린 마음의 개발자가 되려합니다

0개의 댓글