Helper Method Recursion
Helper Method Recursion는 외부 함수(outer function)와 안에 있는 재귀함수, 두 개의 함수를 가지고 있다.
function outer(input){
let outerScopedVariable = [];
function helper(helperInput){
// modify the outerScopedVariable
helper(helperInput--);
}
helper(input);
return outerScopedVariable;
}
Helper Method Recursion는 배열이나 데이터 목록 같은 것을 컴파일(compile)해야 할 때 사용된다. 예를 들어 어떤 배열에서 모든 홀수 값을 수집하는 것과 같은 작업을 수행할 때 Helper Method Recursion를 사용할 수 있다.
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;
}
Pure Recursion
위 예시를 순수 재귀를 사용해서 같은 작업을 수행할 수 있다. 순수 재귀의 경우 필요한 모든 코드가 함수 자체에 포함되며 재귀적이다.
function collectOddValues(arr){
let newArr = [];
if(arr.length === 0) return newArr;
if(arr[0]%2 !== 0){
newArr.push(arr[0]);
}
newArr = newArr.concat(collectOddValues(arr.slice(1)));
return newArr;
}
Pure Recursion Tips!
- 배열을 사용하고 헬퍼 메소드 없이 순수 재귀 솔류션을 작성하는 경우, 배열을 복사하는 slice, spread 연산자(operator), concat 같은 메소드를 사용할 수 있다. 그러면 배열을 변경할 필요가 없다.
- 문자열은 변경할 수 없기 때문에(immutable), slice, substring을 사용해서 사본을 만들어야 한다.
- 객체의 경우, Object.assign이나 spread연산자를 사용하는게 유용하다.
'알고리즘 > 재귀 함수' 카테고리의 다른 글
Recursion(재귀) (0) | 2022.06.24 |
---|---|
Tree UI (0) | 2022.06.24 |