Problem
- Recursive function is a function that calls itself during its execution.
- 재귀(recursive) 함수는, 실행 중에 자신을 호출하는 함수이다.
For example:
function factorial(n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
- Your objective is to complete a recursive function that receives ‘str’ as String and returns the same string in reverse order.
- 역순으로 동일한 문자열을 반환하는 재귀 함수를 작성한다.
- Function should be executed exactly N times.
- Helper functions are not allowed.
Solution 01
function recursiveReverse(str) {
if (str.length <= 1) {
return str;
} else {
return str.slice(-1) + recursiveReverse(str.slice(0, -1));
}
}
recursiveReverse(''); // ''
recursiveReverse('a'); // a
recursiveReverse('abcd'); // dcba
recursiveReverse('1234'); // 4321
slice()
: 문자열/배열의 일부를 추출하고, 새 문자열/배열로 반환한다.
Solution 02
function recursiveReverse(str) {
return str.length > 1 ? str.slice(-1) + recursiveReverse(str.slice(0, -1)) : str;
}
recursiveReverse(''); // ''
recursiveReverse('a'); // a
recursiveReverse('abcd'); // dcba
recursiveReverse('1234'); // 4321
Solution 03
function recursiveReverse(str) {
return str.length > 1 ? recursiveReverse(str.slice(1)) + str[0] : str;
}
recursiveReverse(''); // ''
recursiveReverse('a'); // a
recursiveReverse('abcd'); // dcba
recursiveReverse('1234'); // 4321