똑같은 삽질은 2번 하지 말자
javascript 유명함수를 이용한 재귀 호출 본문
유명함수 란? ↓
유명함수를 이용한 재귀 호출?
어떤 상황에서 활용할 수 있나?
어떤 반복문 내에서 결과를 return하는게 아니라 연산중 return이 발생하는 경우 while문이 종료되버린다.
하지만 while문을 종료시키지 않고 계속 반복하고 싶은 경우에 활용할 수 있다.
코드로 보자면,
/**
take는 즉시실행함수로써 iter에서 내가 원하는 만큼 요소들을 뽑아내는 용
@param l iter에서 가져올 갯수
@param iter iterable
*/
const take = curry((l, iter) => {
let res = []
iter = iter[Symbol.iterator]()
let cur
while (!(cur = iter.next()).done) {
const a = cur.value
if (a instanceof Promise) // 요소가 Promise로 들어올 경우
// 실행해서 리턴시켜줘야한다. 하지만 여기서 return이 일어나므로 함수가 종료되버림
return a.then((a) => {
res.push(a)
if ((res.length = l)) return res
})
res.push(a)
if (res.length == l) return res
}
return res
})
위와 같은 경우 유명함수를 이용한 재귀호출로 의도한 대로의 실행흐름을 만들어 낼 수 있다.
/**
take는 즉시실행함수로써 iter에서 내가 원하는 만큼 요소들을 뽑아내는 용
@param l iter에서 가져올 갯수
@param iter iterable
*/
const take = curry((l, iter) => {
let res = []
iter = iter[Symbol.iterator]()
return function recur() {
let cur
while (!(cur = iter.next()).done) {
const a = cur.value
if (a instanceof Promise)
return a.then((a) => {
res.push(a)
if ((res.length = l)) return res
return recur(); // 다시 while문으로 들어갈 수 있다.
})
res.push(a)
if (res.length == l) return res
}
return res
} ();
})
Comments