Complete memoization/caching solution for JavaScript functions with support for any argument types, async/promise functions, cache expiration, and advanced cache management features
npx @tessl/cli install tessl/npm-memoizee@0.4.0Memoizee is a comprehensive memoization/caching solution for JavaScript functions that provides intelligent function result caching to optimize performance and reduce computational overhead. It supports any type of function arguments without requiring serialization, handles variable-length arguments, works with asynchronous functions and promises, and offers advanced features like cache expiration, LRU-based cache limiting, and sophisticated cache management.
npm install memoizeeconst memoize = require("memoizee");For ES modules:
import memoize from "memoizee";const memoize = require("memoizee");
// Basic function memoization
function expensiveFunction(x, y) {
console.log("Computing...");
return x * y * Math.random();
}
const memoized = memoize(expensiveFunction);
memoized(3, 4); // Computes and caches result
memoized(3, 4); // Returns cached result (no "Computing..." log)Memoizee is built around several key components:
memoize function that creates cached versions of functionsCore memoization functionality that wraps functions to cache their results based on input arguments. Supports configurable argument handling, custom cache key generation, and multiple caching strategies.
/**
* Create a memoized version of a function
* @param {Function} fn - Function to memoize
* @param {Object} options - Configuration options
* @returns {Function} Memoized function with cache management methods
*/
function memoize(fn, options);Specialized memoization for Node.js callback-style functions and promise-returning functions. Handles error cases, prevents caching of failed operations, and supports multiple promise handling modes.
// For callback-style async functions
const memoizedAsync = memoize(asyncFn, { async: true });
// For promise-returning functions
const memoizedPromise = memoize(promiseFn, { promise: true });Advanced cache control features including manual cache manipulation, automatic expiration with pre-fetching, LRU-based size limiting, and reference counting for sophisticated memory management.
// Cache manipulation methods available on memoized functions
memoized.delete(...args); // Delete specific cache entry
memoized.clear(); // Clear all cached entries
memoized._get(...args); // Get cached value without triggering execution
memoized._has(...args); // Check if arguments have cached resultMemory-efficient memoization using WeakMap for garbage collection friendly caching when the first argument is expected to be an object. Cache entries are automatically garbage collected when objects are no longer referenced.
const weakMemoize = require("memoizee/weak");
const memoized = weakMemoize(function(obj) {
return Object.keys(obj).length;
});Specialized utilities for memoizing object methods with lazy property descriptors and proper this context handling. Ideal for prototype method optimization and instance-specific caching.
const memoizeMethods = require("memoizee/methods");
// Usage with property descriptors
Object.defineProperties(MyClass.prototype, memoizeMethods({
expensiveMethod: d(function() { /* method logic */ }, { maxAge: 1000 })
}));Built-in profiling and statistics system that provides detailed insights into cache performance, hit rates, and function call patterns. Essential for optimizing memoization strategies and identifying performance bottlenecks.
const memProfile = require("memoizee/profile");
// Profile statistics and logging
memProfile.statistics; // Raw statistics object
memProfile.log(); // Formatted statistics reportinterface MemoizeOptions {
// Argument handling
length?: number | false; // Override function argument length
primitive?: boolean; // Use primitive mode for string-convertible args
normalizer?: Function; // Custom cache key normalization
resolvers?: Function[]; // Argument type coercion functions
// Asynchronous support
async?: boolean; // Enable for Node.js callback functions
promise?: boolean | string; // Enable for promise functions ("then", "done", etc.)
// Cache expiration
maxAge?: number; // Cache TTL in milliseconds
preFetch?: boolean | number; // Pre-fetch ratio for cache refresh
// Cache size management
max?: number; // Maximum cache entries (LRU eviction)
// Advanced features
refCounter?: boolean; // Enable reference counting
dispose?: Function; // Callback for cache entry disposal
force?: boolean; // Force re-memoization of memoized functions
profileName?: string; // Name for profiling identification
}For functions with primitive arguments that convert to unique strings:
const memoized = memoize(fn, { primitive: true });For object-based functions with automatic cleanup:
const weakMemoize = require("memoizee/weak");
const memoized = weakMemoize(fn);For functions that need fresh data periodically:
const memoized = memoize(fn, {
maxAge: 60000, // 1 minute TTL
preFetch: 0.33 // Refresh when 33% of TTL remains
});For functions with potentially unlimited input variations:
const memoized = memoize(fn, {
max: 100, // Keep only 100 most recent results
dispose: cleanup // Custom cleanup for evicted entries
});