728x90
let list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
function printListReverseLoop(list) {
let cur = list;
const arr = [];
while(cur) {
arr.push(cur.value);
cur = cur.next;
}
for(let i = arr.length - 1; i >= 0; i--) {
console.log(arr[i]);
}
}
function printListReverseRecursion(list) {
if (list.next) {
printListReverseRecursion(list.next);
}
console.log(list.value);
}
printListReverseLoop(list);
printListReverseRecursion(list);
728x90
// loop
function printListLoop(list) {
let cur = list;
while(cur) {
console.log(cur.value);
cur = cur.next;
}
}
// recursion
function printListRecursion(list) {
console.log(list.value);
if (list.next) {
printListRecursion(list.next);
}
}
const list = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: {
value: 4,
next: null
}
}
}
};
console.log('Loop');
printListLoop(list);
console.log('Recursion');
printListRecursion(list);
728x90
function fib(n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib(n -2);
// or
// return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(3)); // 2
console.log(fib(7)); // 13
// console.log(fib(77)); // 5527939700884757(extremely slow!)
function cacheFib(n) {
let a = 1;
let b = 1;
for(let i = 3; i <= n; i++) {
let c = a + b;
a = b;
b = c;
}
return b;
}
console.log(cacheFib(3)); // 2
console.log(cacheFib(7)); // 13
console.log(cacheFib(77)); // 5527939700884757(fast)
728x90
function factorial(n) {
if ( n === 1 ) {
return 1;
}
return n * factorial(n - 1);
// or
// return n === 1 ? 1 : n * factorial(n - 1);
// or
// return n !== 1 ? n * factorial(n - 1) : 1;
// or
// return n ? n * factorial(n - 1) : 1;
}
console.log( factorial(5) ); // 120
728x90
function sumToFromLoop(n) {
let sum = 0;
for(let i = 0; i <= n; i++) {
sum += i;
}
return sum;
}
function sumToRecursion(n) {
if (n === 1) {
return n;
}
return n + sumToRecursion(n - 1);
}
function sumToFormula(n) {
return n * (n + 1) / 2; // 👍🏻
}
console.log( sumToFromLoop(100) ); // 5050
console.log( sumToRecursion(100) ); // 5050
console.log( sumToFormula(100) ); // 5050

+ Recent posts