일급 함수

GoGoDev·2022년 1월 21일
0

JS & TS

목록 보기
6/11

인자로 전달되는 함수

프로그래밍 언어에서 함수라고 하는 코드의 묶음을 일반적인 값처럼 취급하는 개념, 즉 함수를 변수에 넣어서 쓸 수 있다. 이로 인해 일급 함수는 다양한 용도로 쓰일 수 있다.

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)

Console.log 결과

makeLI 함수에는 container와 contents 인자를 받고 string 타입을 반환한다.
container는 string을 받아서 string을 반환하는 함수이다.
contents는 문자열 배열이다.

container 함수는 위에 ul함수와 ol함수와 스펙이 똑같다.

makeLI에 인자가 2개 들어가는데 첫번째 인자는 함수, 두번째 인자는 배열이 들어간다.
htmlUL 같은 경우 첫번째 인자로는 ul함수를 받고 두번째는 요일이 들어간 배열을 받는다.

(일급함수 : 인자로 함수를 넘겨주는 방법)

반환 값으로 전달되는 함수

function salePrice(discountRate, price) {
  return price - price * (discountRate * 0.01);
}

console.log("여름 세일 -" + salePrice(30, 56000));
console.log("겨울 세일 -" + salePrice(10, 56000));

function discrountPrice(discountRate) {
  return function (price) {
    return price - price * (discountRate * 0.01);
  };
}

console.log("여름 세일 -" + discrountPrice(30)(56000)); // 복잡한 값1
console.log("겨울 세일 -" + discrountPrice(10)(56000)); // 복잡한 값2

let summerPrice = discrountPrice(30);
let winterPrice = discrountPrice(10);

console.log("여름 세일 -" + summerPrice(56000));
console.log("겨울 세일 -" + winterPrice(56000));

복잡한 값1에서 discountPrice(30)(56000)함수 에서 discountPrice(30)을 summerPrice 변수에 넣어 사용할 수 있다.
변수로 만들어 사용한다는 것은 이름을 지어서 사용할 수 있고 이는 코드를 쉽게 파악할 수 있는 장점이 있다.

profile
🐣차근차근 무럭무럭🐣

0개의 댓글