CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-emotion--weak-memoize

A memoization function that uses a WeakMap for efficient caching based on object identity

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

@emotion/weak-memoize

@emotion/weak-memoize is a lightweight memoization utility that leverages JavaScript's WeakMap for efficient caching based on object identity. It accepts a single-argument function and returns a memoized version that caches results using the argument object as the key. The WeakMap-based approach ensures memory efficiency by allowing garbage collection of cached entries when the original objects are no longer referenced elsewhere.

Package Information

  • Package Name: @emotion/weak-memoize
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @emotion/weak-memoize

Core Imports

import weakMemoize from "@emotion/weak-memoize";

For CommonJS:

const weakMemoize = require("@emotion/weak-memoize");

Basic Usage

import weakMemoize from "@emotion/weak-memoize";

// Create a memoized function
const memoizedCalculation = weakMemoize((obj: { value: number }) => {
  console.log("Computing expensive operation...");
  return { result: obj.value * 2 };
});

// First call - computation runs
const obj1 = { value: 5 };
const result1 = memoizedCalculation(obj1); // Logs: "Computing expensive operation..."

// Second call with same object reference - returns cached result
const result2 = memoizedCalculation(obj1); // No log - cached result

console.log(result1 === result2); // true

// Different object with same value - computation runs again
const obj2 = { value: 5 };
const result3 = memoizedCalculation(obj2); // Logs: "Computing expensive operation..."

console.log(result1 === result3); // false - different object reference

Capabilities

Memoization Function

Creates a memoized version of a function that caches results using WeakMap for object-based keys.

/**
 * Creates a memoized version of a function using WeakMap for caching
 * @param func - Function to memoize, must accept exactly one object argument
 * @returns Memoized function that caches results by object identity
 */
function weakMemoize<Arg extends object, Return>(
  func: (arg: Arg) => Return
): (arg: Arg) => Return;

Type Parameters:

  • Arg extends object - The argument type, must be a non-primitive (object, function, array, etc.)
  • Return - The return type of the function being memoized

Parameters:

  • func: (arg: Arg) => Return - The function to memoize. Must accept exactly one argument of a non-primitive type.

Returns:

  • (arg: Arg) => Return - A memoized version of the input function

Key Characteristics:

  • WeakMap-based caching: Uses WeakMap internally, allowing garbage collection of unused cache entries
  • Object identity caching: Cache keys are based on object reference equality, not value equality
  • Single argument constraint: The function being memoized must accept exactly one argument
  • Non-primitive arguments only: Arguments must be objects, functions, arrays, or other non-primitive types
  • Memory efficient: Cached entries are automatically garbage collected when the key objects are no longer referenced

Usage Examples:

import weakMemoize from "@emotion/weak-memoize";

// Memoizing expensive object transformations
const processData = weakMemoize((data: { items: any[] }) => {
  return data.items.map(item => expensiveTransformation(item));
});

// Memoizing React component prop calculations
const calculateProps = weakMemoize((config: ComponentConfig) => {
  return {
    className: generateClassName(config),
    styles: computeStyles(config),
    handlers: createEventHandlers(config)
  };
});

// Memoizing function results based on function identity
const memoizeByFunction = weakMemoize((fn: Function) => {
  return fn.toString().length; // Cache function string length
});

Type Constraints:

The following types are not allowed as arguments (will cause TypeScript compilation errors):

  • string
  • number
  • boolean
  • symbol
  • null
  • undefined

The following types are allowed as arguments:

  • Objects: {}
  • Arrays: any[]
  • Functions: () => any
  • Classes: class instances
  • Built-in objects: Map, Set, Date, etc.

Error Handling:

The function does not throw runtime errors, but TypeScript will prevent compilation if:

  • The function argument is not a single parameter
  • The argument type is a primitive type
  • The argument type does not extend object

Performance Considerations:

  • Memory efficient: WeakMap allows automatic garbage collection of cached entries
  • Fast lookups: O(1) cache lookup performance
  • Reference-based: Only caches based on object identity, not deep equality
  • Optimal for component libraries: Particularly useful in React/emotion context where object references are stable within render cycles
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@emotion/weak-memoize@0.4.x
Publish Source
CLI
Badge
tessl/npm-emotion--weak-memoize badge