Skip to content

feat: Add @memoize decorator for caching method results#268

Merged
guyca merged 4 commits intomasterfrom
feat/memoize-decorator
Jan 20, 2026
Merged

feat: Add @memoize decorator for caching method results#268
guyca merged 4 commits intomasterfrom
feat/memoize-decorator

Conversation

@guyca
Copy link
Copy Markdown
Collaborator

@guyca guyca commented Jan 19, 2026

Summary

Add a new @memoize() decorator that caches method return values based on arguments, avoiding redundant computations for expensive operations.

  • Supports both modern TC39 and legacy TypeScript decorator syntax
  • Per-instance caching (each class instance maintains its own cache)
  • Uses Object.is comparison (like React.useMemo) instead of JSON.stringify
  • Single-value cache (caches only the last result)
  • Optional custom isEqual function for specialized comparison logic

Usage

// Default: Object.is comparison for each argument
@memoize()
computeValue(a: number, b: number): number { ... }

// Custom equality function
@memoize({ isEqual: (newArgs, lastArgs) => newArgs[0].id === lastArgs[0].id })
getUserData(user: User): Data { ... }

Test plan

  • Unit tests for caching behavior (same args return cached value)
  • Tests for single-value cache behavior (eviction on different args)
  • Tests for per-instance cache isolation
  • Tests for various return types (objects, arrays, strings)
  • Tests for Object.is edge cases (NaN, -0)
  • Tests for custom isEqual function

guyca added 4 commits January 19, 2026 21:46
Add a new decorator that caches method return values based on arguments.
Supports both modern TC39 and legacy TypeScript decorator syntax.
- Replace JSON.stringify with Object.is-based comparison (like React.useMemo)
- Change from multi-value cache to single-value cache
- Add optional isEqual parameter for custom equality functions
- Update tests for new behavior and edge cases (NaN, -0)
@guyca guyca merged commit 84b7fa3 into master Jan 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant