LRU Memoization Utility

1.1.0 · active · verified Sun Apr 19

`lru-memoize` is a utility library for JavaScript and TypeScript that provides simple memoization for pure functions using an LRU (Least Recently Used) cache. It helps optimize performance by storing results of expensive function calls and returning the cached result when the same inputs occur again. The current stable version is 1.1.0, released recently with bug fixes and explicit TypeScript/Flow support. The package features a configurable cache limit, custom equality comparison functions, and an option for deep object comparison for arguments, making it flexible for various use cases. Its primary differentiation lies in its minimalist approach to LRU caching for functions, focusing on purity and avoiding side effects. The release cadence appears to be driven by bug fixes and improvements rather than frequent new features, ensuring stability over rapid, breaking changes.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to apply `lru-memoize` to a pure function, configuring a specific cache limit. It illustrates when a function is executed versus when its result is retrieved from the LRU cache, including how older entries are evicted.

import memoize from 'lru-memoize';

// A "pure" function to be memoized. It calculates the product of three numbers.
// We add a console log to demonstrate when the actual calculation occurs.
const multiply = (a: number, b: number, c: number): number => {
  console.log(`Calculating for ${a}, ${b}, ${c}...`); // Shows when the function actually runs
  return a * b * c;
};

// Memoize the 'multiply' function with a cache limit of 2.
// This means it will remember the last 2 unique sets of arguments and their results.
const memoizedMultiply = memoize(2)(multiply);

console.log('--- Demonstrating Cache Hits and Evictions ---');
console.log('1. First call:', memoizedMultiply(2, 3, 4)); // Calculates: (24) -> cache: [(2,3,4):24]
console.log('2. Second call:', memoizedMultiply(5, 6, 7)); // Calculates: (210) -> cache: [(5,6,7):210, (2,3,4):24]
console.log('3. First call again (cached):', memoizedMultiply(2, 3, 4)); // Hits cache -> cache: [(2,3,4):24, (5,6,7):210]
console.log('4. New call (evicts oldest):', memoizedMultiply(1, 2, 3)); // Calculates: (6) -> cache: [(1,2,3):6, (2,3,4):24]
console.log('5. Second call again (cached):', memoizedMultiply(5, 6, 7)); // Calculates (was evicted) -> cache: [(5,6,7):210, (1,2,3):6] 
console.log('6. First call again (evicted, re-calculates):', memoizedMultiply(2, 3, 4)); // Calculates -> cache: [(2,3,4):24, (5,6,7):210]

view raw JSON →