간단정리
[JS] 고차 함수 (Higher-Order Function)
RyuK-H
2020. 10. 22. 20:00
내가 고차 함수를 찾아보게 된 계기는 데코레이터를 검색하다, 고차 함수에 대한 보다 더 정확하게 이해하고 싶게 되어서이다.
고차 함수란?
고차 함수는 함수를 인자로 전달 받거나, 함수를 반환 하는 함수를 의미한다.
고차 함수는 꼭 자바스크립트에 한정 되어있지 않고, 대부분의 언어에서 지원하고 또 비슷한 방식으로 구현 할 수 있다. (위키 `고차 함수`)
[예제] 고차 함수는 함수를 인자로 전달 받는다.
// 갓챠 함수는 함수를 인자로 전달 받는다. (고차, 가챠 라임ㅎㅎ)
function Gacha(func/*: Function*/, value/*: number*/) {
console.log(func(value));
}
function Squared(value/*: number*/) {
return value * value;
}
Gacha(Squared, 5);
난 아직까지 타입이 명시 되어있는 자바스크립트를 읽는 것에 익숙하지는 않다. 하지만, 자바스크립트로 예제를 작성해보자면 위와 같을 것이다. 사실 알게 모르게 웹 개발을 하면서 꽤 다양한 종류의 고차 함수를 썼던 것 같다. 콜백 함수를 넘겨 주거나, 타입스크립트의 타입 검사를 위해 함수를 인자로 넘겨주거나. 그래서 알고 보면 굉장히 친숙한 친구 같다.
[예제] 고차 함수는 함수를 반환 한다.
// ES5 array.sort
// sort(compareFn?: (a: T, b: T) => number): this;
/**
* Sorts an array.
* @param compareFn Function used to determine the order of the elements. It is expected to return
* a negative value if first argument is less than second argument, zero if they're equal and a positive
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
* ```ts
* [11,2,22,1].sort((a, b) => a - b)
* ```
*/
// 예제 비교 함수
const todos = [
{ id: 4, content: "JavaScript" },
{ id: 1, content: "HTML" },
{ id: 2, content: "CSS" },
];
function compare(key) {
return function (a, b) {
return a[key] > b[key] ? 1 : (a[key] < b[key] ? -1 : 0);
};
};
todos.sort(compare("id"));
console.log(todos);
함수 반환을 할 수 있는 고차함수의 경우 위와 같이 함수를 인자로 요구하는 고차함수를 위해 활용할 수 있을 것 같다. Array.sort 외에도 Array.forEach, Array.map에도 활용할 수 있다.
참고