함수가 함수를 반환하는 패턴은 좀 복잡한 편입니다. 함수를 반환하는 함수의 예제를 더 보고
싶다면 자바스크립트 웹 개발 프레임워크로 널리 쓰이는 익스프레스
Express
나
Koa
같은 미들웨
어 패키지를 살펴보십시오. 미들웨어는 대개 함수를 반환하는 함수 형태로 만들어집니다.
13.7
재귀
재귀
recursion
역시 널리 쓰이며 함수를 활용하는 중요한 패턴입니다. 재귀란 자기 자신을 호출하
는 함수입니다. 같은 일을 반복하면서 그 대상이 점차 줄어드는 상황에서 재귀를 유용하게 활
용할 수 있습니다.
먼저 건초 더미
haystack
에서 바늘
needle
을 찾는, 좀 인위적인 예제를 하나 봅시다. 실제로 건초 더
미에서 바늘을 찾아야 하는 상황이라면 아마 이런 식으로 찾아볼 겁니다.
1
. 건초 더미에서 바늘이 보이면
3
단계로 이동한다.
2
. 건초 더미에서 건초
hay
를 하나 덜어낸다.
1
단계로 이동한다.
3
. 찾았다!
결국 바늘을 찾을 때까지 건초 더미에서 건초를 하나씩 제외하는 소거법이며, 이것이 재귀입니
다. 이 행동을 코드로 바꿔 봅시다.
function
findNeedle
(
haystack
) {
if
(
haystack
.
length
===
0
)
return
"
no
haystack
here
!";
if
(
haystack
.
shift
() === '
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.