or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

async-functions.mdcache-management.mdfunction-memoization.mdindex.mdmethod-memoization.mdprofiling.mdweakmap-memoization.md
tile.json

tessl/npm-memoizee

Complete memoization/caching solution for JavaScript functions with support for any argument types, async/promise functions, cache expiration, and advanced cache management features

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/memoizee@0.4.x

To install, run

npx @tessl/cli install tessl/npm-memoizee@0.4.0

index.mddocs/

Memoizee

Memoizee 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.

Package Information

  • Package Name: memoizee
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install memoizee

Core Imports

const memoize = require("memoizee");

For ES modules:

import memoize from "memoizee";

Basic Usage

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)

Architecture

Memoizee is built around several key components:

  • Core Memoization: Main memoize function that creates cached versions of functions
  • Configuration System: Extensive options for customizing caching behavior and performance characteristics
  • Extension Architecture: Modular extensions for async functions, promises, cache expiration, and advanced features
  • Multiple Cache Strategies: Support for primitive mode, object mode, and WeakMap-based caching
  • Cache Management: Manual cache control, automatic expiration, LRU eviction, and reference counting

Capabilities

Function Memoization

Core 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);

Function Memoization

Asynchronous Function Support

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 });

Asynchronous Functions

Cache Management

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 result

Cache Management

WeakMap-Based Memoization

Memory-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;
});

WeakMap Memoization

Method Memoization

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 })
}));

Method Memoization

Performance Profiling

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 report

Performance Profiling

Configuration Options

interface 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
}

Common Patterns

High-Performance Caching

For functions with primitive arguments that convert to unique strings:

const memoized = memoize(fn, { primitive: true });

Memory-Conscious Caching

For object-based functions with automatic cleanup:

const weakMemoize = require("memoizee/weak");
const memoized = weakMemoize(fn);

Time-Based Cache Invalidation

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
});

Size-Limited Cache

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
});