recursion : a process (a function) that calls itself
function outer(input) {
let outerScopedVariable = [];
function helper(helperInput) {
// modify the outerScopedVaraible
helper(helperInput--);
}
helper(input);
return outerScopedVariable;
}
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]);
slice
, spread operator
, concat
등의 메서드를 사용하여 array의 복사본을 만들기 (array를 변형시키지 말 것)slice
, substr
, substring
등의 메소드를 사용하여 string의 복사본을 만들기 (string은 immutable함)Object.assign
, spread operator
를 사용하여 object의 복사본을 반들기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;
}
function power(base, exponent){
if (exponent === 0) return 1;
return base * power(base, exponent - 1);
}
function factorial(num){
if (num === 0) return 1;
return num * factorial(num - 1);
}
function productOfArray(arr) {
let result = 1;
function helper(helperInput) {
if (helperInput.length === 0) return;
result *= helperInput[0];
helper(helperInput.slice(1));
}
helper(arr);
return result;
function recursiveRange(num){
if (num === 0) return 0;
return num + recursiveRange(num - 1);
}
function fib(num){
if (num <= 2) return 1;
return fib(num - 1) + fib(num - 2);
}