javascript / intermediate
Snippet
Higher-Order Functions for Memoization
Memoization is an optimization technique where you store the results of expensive function calls and return the cached result when the same inputs occur again.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
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;};};
Breakdown
1
const cache = new Map();
Creates a persistent storage for results using a closure.
2
if (cache.has(key)) return cache.get(key);
Checks if the computation has already been performed for these specific arguments.