es-next-tools
Version:
A comprehensive utility library for JavaScript and TypeScript that provides a wide range of functions for common programming tasks, including mathematical operations, date manipulations, array and object handling, string utilities, and more.
32 lines (31 loc) • 1 kB
JavaScript
/**
* Creates a memoized version of a function.
* @param {T} fn - The function to memoize.
* @returns {(...args: Parameters<T>) => ReturnType<T> | undefined} A memoized version of the input function.
* @template T
* @example
* const expensiveCalculation = (n) => {
* console.log('Calculating...');
* return n * 2;
* };
* const memoizedCalc = memoize(expensiveCalculation);
*
* console.log(memoizedCalc(5)); // Logs: Calculating... 10
* console.log(memoizedCalc(5)); // Logs: 10 (no calculation, result from cache)
*/
export function memoize(fn, limit = 100) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) {
if (cache.size >= limit) {
const firstKey = cache.keys().next().value;
if (firstKey) {
cache.delete(firstKey);
}
}
cache.set(key, fn(...args));
}
return cache.get(key);
};
}