TypeScript Method Memoization Decorator

1.1.1 · active · verified Sun Apr 19

typescript-memoize is a decorator library for TypeScript that enables method and getter memoization, primarily for optimizing performance by caching the results of expensive operations. As of version 1.1.1, it provides `@Memoize` for standard caching and `@MemoizeExpiring` for time-limited caching, which automatically invalidates cached values after a specified duration. The library offers flexibility in how memoization keys are generated, supporting methods without parameters, `get` accessors, and methods where memoization is based on specific parameters or custom hash functions. It's a stable library, though release cadence is not explicitly defined, new versions appear infrequently. Its key differentiator lies in its decorator-based approach, integrating seamlessly with TypeScript classes, and allowing for granular control over cache invalidation via custom hash functions or expiration.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic `@Memoize`, `@MemoizeExpiring` with a time limit, and `@Memoize` with a custom hash function for complex parameters, showing cache hits and expirations in a class context.

import { Memoize, MemoizeExpiring } from 'typescript-memoize';

class DataService {
    private callCount: number = 0;

    @Memoize()
    public getExpensiveData(): string {
        this.callCount++;
        console.log(`Fetching expensive data... (call count: ${this.callCount})`);
        return `Data fetched at ${new Date().toISOString()}`;
    }

    @MemoizeExpiring(3000) // Cache expires after 3 seconds
    public getExpiringData(param: string): string {
        console.log(`Fetching expiring data for '${param}'...`);
        return `Expiring data for ${param} at ${new Date().toISOString()}`;
    }

    // Custom hash function for memoizing based on multiple parameters
    @Memoize((id: number, type: string) => `${id}-${type}`)
    public getItem(id: number, type: string): string {
        console.log(`Fetching item ${id} of type ${type}...`);
        return `Item ${id} (${type}) retrieved at ${new Date().toISOString()}`;
    }
}

async function runExample() {
    const service = new DataService();

    console.log("--- Standard Memoize ---");
    console.log(service.getExpensiveData()); // Fetches
    console.log(service.getExpensiveData()); // Returns cached
    console.log(service.getExpensiveData()); // Returns cached

    console.log("\n--- Expiring Memoize ---");
    console.log(service.getExpiringData("A")); // Fetches
    console.log(service.getExpiringData("A")); // Returns cached
    await new Promise(resolve => setTimeout(resolve, 3100)); // Wait for cache to expire
    console.log(service.getExpiringData("A")); // Fetches again after expiration

    console.log("\n--- Custom Hash Function Memoize ---");
    console.log(service.getItem(1, "book")); // Fetches
    console.log(service.getItem(1, "book")); // Returns cached
    console.log(service.getItem(2, "book")); // Different key, fetches
    console.log(service.getItem(1, "movie")); // Different key, fetches
}

runExample();

view raw JSON →