CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-moize

Blazing fast memoization library for JavaScript with comprehensive configuration options and React support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

cache-management.mddocs/

Cache Management

Methods for controlling cache size limits, time-to-live expiration, and argument handling to optimize memory usage and performance.

Capabilities

Infinite Cache Size

Remove all limits from cache size, allowing unlimited entries.

/**
 * Memoization with unlimited cache size
 * @returns Moizer with no cache size limit
 */
infinite: Moizer;

Usage Examples:

import moize from "moize";

const fibonacci = (n: number): number => {
  if (n < 2) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
};

// Cache all fibonacci calculations indefinitely
const memoizedFib = moize.infinite(fibonacci);

console.log(memoizedFib(100)); // All intermediate values cached

Maximum Cache Size

Set the maximum number of entries that can be stored in the cache.

/**
 * Set maximum cache size
 * @param size Maximum number of cache entries
 * @returns Moizer with specified maximum cache size
 */
maxSize<MaxSize extends number>(size: MaxSize): Moizer<{ maxSize: MaxSize }>;

Usage Examples:

const expensiveOperation = (data: string) => {
  // Simulate expensive computation
  return data.split('').reverse().join('').toUpperCase();
};

// Keep only the 5 most recent results
const memoized = moize.maxSize(5)(expensiveOperation);

// After 6 calls, the first result will be evicted
for (let i = 1; i <= 6; i++) {
  console.log(memoized(`input${i}`));
}

Maximum Arguments

Limit the number of arguments used for determining the cache key.

/**
 * Limit the number of arguments used for cache key generation
 * @param args Number of arguments to consider for caching
 * @returns Moizer with limited argument consideration
 */
maxArgs<MaxArgs extends number>(args: MaxArgs): Moizer<{ maxArgs: MaxArgs }>;

Usage Examples:

const processData = (
  primaryData: string,
  secondaryData: string,
  debugInfo?: any,
  metadata?: any
) => {
  return `${primaryData}-${secondaryData}`;
};

// Only use first 2 arguments for caching
const memoized = moize.maxArgs(2)(processData);

console.log(memoized("a", "b", { debug: true }, { env: "prod" })); // Computed
console.log(memoized("a", "b", { debug: false }, { env: "dev" })); // Cached (same first 2 args)
console.log(memoized("a", "c", { debug: true }, { env: "prod" })); // Computed (different 2nd arg)

Time-to-Live (TTL) with maxAge

Set expiration time for cached values with comprehensive expiration handling.

interface MaxAge {
  /**
   * Set TTL in milliseconds
   * @param maxAge Time to live in milliseconds
   * @returns Moizer with TTL configuration
   */
  <MaxAge extends number>(maxAge: MaxAge): Moizer<{ maxAge: MaxAge }>;
  
  /**
   * Set TTL with expiration update behavior
   * @param maxAge Time to live in milliseconds
   * @param expireOptions Whether to update expiration on cache hit
   * @returns Moizer with TTL and update expiration configuration
   */
  <MaxAge extends number, UpdateExpire extends boolean>(
    maxAge: MaxAge,
    expireOptions: UpdateExpire
  ): Moizer<{ maxAge: MaxAge; updateExpire: UpdateExpire }>;
  
  /**
   * Set TTL with expiration callback
   * @param maxAge Time to live in milliseconds
   * @param expireOptions Function called when cache entry expires
   * @returns Moizer with TTL and expiration callback
   */
  <MaxAge extends number, ExpireHandler extends OnExpire>(
    maxAge: MaxAge,
    expireOptions: ExpireHandler
  ): Moizer<{ maxAge: MaxAge; onExpire: ExpireHandler }>;
  
  /**
   * Set TTL with expiration options object
   * @param maxAge Time to live in milliseconds
   * @param expireOptions Configuration object with onExpire and/or updateExpire
   * @returns Moizer with comprehensive TTL configuration
   */
  <MaxAge extends number, ExpireHandler extends OnExpire, UpdateExpire extends boolean>(
    maxAge: MaxAge,
    expireOptions: {
      onExpire?: ExpireHandler;
      updateExpire?: UpdateExpire;
    }
  ): Moizer<{ maxAge: MaxAge; onExpire: ExpireHandler; updateExpire: UpdateExpire }>;
}

type OnExpire = (key: Key) => any;
type Key<Arg extends any = any> = Arg[];

Usage Examples:

import moize from "moize";

// Basic TTL - expire after 5 seconds
const fetchData = async (id: string) => {
  const response = await fetch(`/api/data/${id}`);
  return response.json();
};

const cachedFetch = moize.maxAge(5000)(fetchData);

// TTL with expiration update - refresh TTL on each access
const memoizedWithRefresh = moize.maxAge(10000, true)(fetchData);

// TTL with expiration callback
const memoizedWithCallback = moize.maxAge(3000, (key) => {
  console.log(`Cache expired for key:`, key);
})(fetchData);

// TTL with comprehensive options
const memoizedComprehensive = moize.maxAge(15000, {
  updateExpire: true,
  onExpire: (key) => {
    console.log(`Expired:`, key);
    // Could trigger background refresh here
  }
})(fetchData);

// Using with promise memoization
const promiseMemoized = moize.promise.maxAge(30000)(fetchData);

Expiration Management

Direct control over cache entry expiration.

type Expiration = {
  /** Function to execute when expiration occurs */
  expirationMethod: () => void;
  /** The cache key that will expire */
  key: Key;
  /** Timer ID for the expiration timeout */
  timeoutId: ReturnType<typeof setTimeout>;
};

Combining Cache Management Methods

Cache management methods can be chained together for comprehensive control.

import moize from "moize";

const heavyComputation = (data: any[], options: any) => {
  return data
    .filter(options.filter)
    .map(options.transform)
    .reduce(options.reduce, options.initialValue);
};

// Combined cache management: size limit, TTL, and argument limit
const optimizedMemoized = moize
  .maxSize(20)           // Keep up to 20 entries
  .maxAge(60000)         // Expire after 1 minute
  .maxArgs(1)            // Only use first argument for cache key
  .deep                  // Use deep equality for the data array
  (heavyComputation);

// With profiling and expiration callback
const monitoredMemoized = moize
  .maxSize(10)
  .maxAge(30000, {
    updateExpire: true,
    onExpire: (key) => console.log('Expired:', key)
  })
  .profile('heavy-computation')
  (heavyComputation);

Cache Size Considerations

Default cache size is 1, meaning only the most recent result is cached unless explicitly configured.

const defaultMemoized = moize(someFunction); // maxSize: 1 by default

const configuredMemoized = moize(someFunction, {
  maxSize: 100  // Explicitly set larger cache
});

// Or using fluent API
const fluentMemoized = moize.maxSize(100)(someFunction);

docs

argument-transformation.md

cache-introspection.md

cache-management.md

core-memoization.md

equality-comparison.md

index.md

specialized-memoization.md

statistics-profiling.md

utility-methods.md

tile.json