유의할 점
base case
는 필수 (The base case
returns a value without making any subsequent recursive call.)
return
statement
Recursive Factorial
const factorial = (n) => {
let total = 1;
for(let i=n; i>1; i--) {
total *= i;
}
return total;
}
const factorial = (n) => {
if(n === 1) return 1;
return n * factorial(n-1)
}
Helper method recursion
패턴
const outer = (input) => {
let outerScopeVariable = [];
const helper = (helperInput) => {
helper(helperInput--);
}
helper(input);
return outerScopeVariable;
}
예시
function collectOddValues(arr){
let result = [];
function helper(helperInput){
if(helperInput.length === 0) {
return;
}
if(helperInput[0] % 2 !== 0){
result.push(helperInput[0])
}
helper(helperInput.slice(1))
}
helper(arr)
return result;
}
collectOddValues([1,2,3,4,5,6,7,8,9])