Last active
February 21, 2024 01:31
-
-
Save AnandPilania/1c0e084681c47cd74367e8afc2c521aa to your computer and use it in GitHub Desktop.
Memoize a function
This file contains 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
const memoize = (fn: any) => | |
( | |
(cache = Object.create(null)) => | |
(arg: any) => | |
cache[arg] || (cache[arg] = fn(arg)) | |
)(); | |
// Calculate Fibonacci numbers | |
// const fibo = memoize((n: number) => (n <= 2 ? 1 : fibo(n - 1) + fibo(n - 2))); | |
// fibo(1); // 1 | |
// fibo(2); // 1 | |
// fibo(3); // 2 | |
// fibo(4); // 3 | |
// fibo(5); // 5 | |
// fibo(6); // 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment