JS 인터뷰 2분/Higher Order Functions
Javascript의 고차 함수를 설명하십시오.
빠른 답변:
다른 함수를 반환하는 함수입니다.
UPD: 주석에서 언급했듯이 고차 함수는 함수를 매개변수로 받아들이는 함수이기도 합니다. Wikipedia
더 긴 답변:
JavaScript에서는 함수의 결과로 모든 유형의 개체를 반환하거나 모든 유형의 개체를 매개 변수로 받을 수 있습니다. 즉, 함수를 반환하는 함수를 만들 수 있습니다.
function higherFunction() {
return function regularFunction() {
console.log('Hello world!')
}
}
const a = higherFunction() // won't print anything
a() // Hello world!
더 많은 중첩 함수를 만들 수도 있습니다.
const a = () => () => () => () => console.log('Hello world')
const b = a()
const c = b()
const d = c()
d() // Hello world!
특정 순서로 함수를 실행할 함수에 함수를 전달할 수 있습니다.
const pipe = (...args) =>
(init) =>
args.reduce((acc, cur) => cur(acc), init)
const a = pipe(
(val) => val + 1,
(val) => val * 2,
(val) => console.log("Got", val),
)
a(10) // Got 22
기능을 사용하는 다른 재미있는 방법 🤪
실생활 예:
일부 프레임워크( angular ) 및 라이브러리( MobX )는 데코레이터에 크게 의존하지만 데코레이터는 고차 함수 그 자체에 불과합니다.
const logDecorator = (wrapped) => {
return (...args) => {
console.log(`Invoked ${wrapped.name} with args ${args}`)
wrapped(...args)
}
}
const tmp = (param) => {
console.log('Do nothing, but just show param:', param)
}
const wrappedTmp = logDecorator(tmp)
wrappedTmp('Hello world!')
// Invoked tmp with args Hello world!
// Do nothing, but just show param: Hello world!
일부 다른 라이브러리( RxJs )는 구성 가능한 도우미로 사용할 수 있습니다.
// These functions can by provided by a library itself
const uppercase = (a) => a.toUpperCase();
const removePunctuation = (a) => a.replace(/[^0-9a-zA-Z ]/g, '')
// pipe is a Higher Order Function that returns a function, which will apply all functions one by one
const process = pipe(
uppercase,
removePunctuation,
)
console.log(process('qwe-qwe'), process('Hello world!'))
// QWEQWE HELLO WORLD
이전 게시물:
Btw, 나는 여기와에 더 재미있는 것을 게시 할 것입니다. 친구하자👋
Reference
이 문제에 관하여(JS 인터뷰 2분/Higher Order Functions), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/kozlovzxc/js-interview-in-2-minutes-higher-order-functions-38kb텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)