Last active
February 15, 2026 11:33
-
-
Save espio999/3b14a623cf444ceb4cf76b1a68b56e9c to your computer and use it in GitHub Desktop.
Fibonacci in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*function memoization(func){ | |
| let memo = new Map(); | |
| console.log(`counter: ${memo.size}`); | |
| function memoize(arg){ | |
| console.log(`${arg} is received`); | |
| let isExist = memo.get(arg); | |
| if (isExist) { | |
| return isExist; | |
| } | |
| else{ | |
| let v = func(arg); | |
| memo.set(arg, v); | |
| return v; | |
| } | |
| } | |
| return memoize; | |
| }*/ | |
| function memoization(func){ | |
| let memo = new Map(); | |
| console.log(`counter: ${memo.size}`); | |
| function memoize(...args){ | |
| console.log(`${args} is received`); | |
| const key = JSON.stringify(args); | |
| if (memo.has(key)){ | |
| console.log(`Cache hit: ${key}`); | |
| return memo.get(key); | |
| } | |
| else{ | |
| const v = func.apply(this, args); | |
| memo.set(key, v); | |
| return v; | |
| } | |
| } | |
| return memoize; | |
| } | |
| function fibonacci(num){ | |
| switch(num){ | |
| case 0: | |
| case 1: | |
| return num; | |
| break; | |
| default: | |
| return fibonacci(num - 1) + fibonacci(num - 2); | |
| } | |
| } | |
| function memoized_fibonacci(num){ | |
| let memo = new Map(); | |
| function fibonacci_inline(num){ | |
| let isExist = memo.get(num); | |
| if (isExist === undefined){ | |
| switch(num){ | |
| case 0: | |
| case 1: | |
| return num; | |
| default: | |
| let v = fibonacci_inline(num - 1) + fibonacci_inline(num - 2); | |
| memo.set(num, v); | |
| return v; | |
| } | |
| } | |
| else{ | |
| //console.log(`cache hit!! - ${isExist}`); | |
| return isExist; | |
| } | |
| } | |
| return fibonacci_inline(num); | |
| } | |
| function tail_rec_fibonacci(num){ | |
| function loop(acc1, acc2, num){ | |
| switch(num){ | |
| case 0: | |
| return acc1; | |
| case 1: | |
| return acc2; | |
| default: | |
| return loop(acc2, acc1 + acc2, num - 1); | |
| } | |
| } | |
| return loop(0, 1, num); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment