javascript / intermediate
Snippet
Implementing a Simple Memoization Cache
Memoization is a technique to optimize functions by caching their results based on input arguments. For expensive recursive or repetitive operations, this can transform exponential time complexity into linear complexity.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const memoize = (fn) => {const cache = new Map();return (...args) => {const key = JSON.stringify(args);if (cache.has(key)) return cache.get(key);const result = fn(...args);cache.set(key, result);return result;};};const fibonacci = memoize((n) => {return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);});
nodejs
Breakdown
1
const cache = new Map();
Uses a Map to store results of previous function calls.
2
const key = JSON.stringify(args);
Generates a unique cache key based on the input arguments.
3
if (cache.has(key)) return cache.get(key);
Returns the pre-calculated value if it exists in the cache.