Skip to content

Instantly share code, notes, and snippets.

@AnandPilania
Last active February 21, 2024 01:31
Show Gist options
  • Save AnandPilania/1c0e084681c47cd74367e8afc2c521aa to your computer and use it in GitHub Desktop.
Save AnandPilania/1c0e084681c47cd74367e8afc2c521aa to your computer and use it in GitHub Desktop.
Memoize a function
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