Skip to content

Instantly share code, notes, and snippets.

View gpDA's full-sized avatar
🏠
Working from home

GP LEE gpDA

🏠
Working from home
View GitHub Profile
function fill(times, number) {
if (times <= 0) return [];
return [number].concat(fill(times -1, number));
}
console.log(fill(5, 2)); // [2, 2, 2, 2, 2]
function recLen(str) {
if (str == '') return 0
return recLen(str.substring(1)) + 1;
}
let str ="abcd";
console.log(recLen(str));
function getElementsByClassName(className) {
const results = [];
const checkRecursive = (element, cName) => {
const cn = element.getAttribute("class");
if (cn !== undefined && cn !== null && cn.includes(cName)) {
results.push(element);
}
// element.children MDN
if (element.children.length > 0) {
function flatten(arr, ret = []) {
for (const entry of arr) {
if (Array.isArray(entry)) {
flatten(entry, ret)
} else {
ret.push(entry)
}
}
return ret;
}
const findFibonacci = (n) => {
if (n == 1) return [0, 1];
let res = findFibonacci(n-1);
res.push(res[res.length - 1] + res[res.length - 2])
return res;
}
console.log(findFibonacci(5)); // [0, 1, 1, 2, 3, 5]
// recursion
const recursiveFindRange = (low, high) => {
if (low === high - 2) return [high - 1];
let res = recursiveFindRange(low, high - 1)
res.push(high - 1);
return res;
};
const recursiveDigitSum = (number) => {
if (number === 0) return 0;
return number % 10 + recursiveDigitSum(Math.floor(number / 10))
}
const factorialNumber = (num) => {
if (num === 1) return 1;
return num * factorialNumber(num - 1);
}
console.log(factorialNumber(5)); // 120
function fibonacci(num) {
if(num < 2) {
return num;
}
else {
return fibonacci(num-1) + fibonacci(num - 2);
}
}
// recursion 1 - using helper function
const RecursiveHelperProductArr = (arr) => {
let index = arr.length - 1;
// helper function
const recur = (curIndex, acc) => {
acc *= arr[curIndex];
if (curIndex === 0) return acc;
return recur(curIndex - 1, acc); // decrement the index and recursion
}