|
| 1 | +/** |
| 2 | + * Options for memoization |
| 3 | + */ |
| 4 | +export interface MemoizeOptions { |
| 5 | + /** |
| 6 | + * Maximum number of cached results to store |
| 7 | + * @default 100 |
| 8 | + */ |
| 9 | + maxSize?: number; |
| 10 | + /** |
| 11 | + * Custom key generator for cache keys |
| 12 | + * @default JSON.stringify for multiple args, toString for single arg |
| 13 | + */ |
| 14 | + getKey?: (...args: any[]) => string; |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Creates a memoized version of a function with LRU cache eviction. |
| 19 | + * Useful for expensive operations like levenshtein distance or fuzzy matching. |
| 20 | + * |
| 21 | + * @param fn - The function to memoize |
| 22 | + * @param options - Optional configuration for memoization behavior |
| 23 | + * @returns A memoized version of the input function |
| 24 | + * |
| 25 | + * @example |
| 26 | + * ```ts |
| 27 | + * // Basic usage |
| 28 | + * const expensiveFn = (n: number) => { |
| 29 | + * console.log('Computing...'); |
| 30 | + * return n * n; |
| 31 | + * }; |
| 32 | + * const memoized = memoize(expensiveFn); |
| 33 | + * memoized(5); // Computing... → 25 |
| 34 | + * memoized(5); // → 25 (cached, no "Computing...") |
| 35 | + * |
| 36 | + * // With string utilities |
| 37 | + * import { levenshtein, memoize } from 'nano-string-utils'; |
| 38 | + * const fastLevenshtein = memoize(levenshtein); |
| 39 | + * |
| 40 | + * // Process many comparisons efficiently |
| 41 | + * const words = ['hello', 'hallo', 'hola']; |
| 42 | + * words.forEach(word => { |
| 43 | + * fastLevenshtein('hello', word); // Cached after first call |
| 44 | + * }); |
| 45 | + * |
| 46 | + * // Custom cache size |
| 47 | + * const limited = memoize(expensiveFn, { maxSize: 10 }); |
| 48 | + * |
| 49 | + * // Custom key generation (for objects) |
| 50 | + * const processUser = (user: { id: number; name: string }) => { |
| 51 | + * return `User: ${user.name}`; |
| 52 | + * }; |
| 53 | + * const memoizedUser = memoize(processUser, { |
| 54 | + * getKey: (user) => user.id.toString() |
| 55 | + * }); |
| 56 | + * ``` |
| 57 | + */ |
| 58 | +export function memoize<T extends (...args: any[]) => any>( |
| 59 | + fn: T, |
| 60 | + options: MemoizeOptions = {} |
| 61 | +): T { |
| 62 | + const { maxSize = 100, getKey } = options; |
| 63 | + |
| 64 | + // Use Map for O(1) lookups with insertion order tracking |
| 65 | + const cache = new Map<string, any>(); |
| 66 | + |
| 67 | + // Default key generator |
| 68 | + const generateKey = |
| 69 | + getKey || |
| 70 | + ((...args: any[]): string => { |
| 71 | + if (args.length === 0) return ""; |
| 72 | + if (args.length === 1) { |
| 73 | + const arg = args[0]; |
| 74 | + // Handle null and undefined specially |
| 75 | + if (arg === null) return "__null__"; |
| 76 | + if (arg === undefined) return "__undefined__"; |
| 77 | + // Fast path for primitives |
| 78 | + if ( |
| 79 | + typeof arg === "string" || |
| 80 | + typeof arg === "number" || |
| 81 | + typeof arg === "boolean" |
| 82 | + ) { |
| 83 | + return String(arg); |
| 84 | + } |
| 85 | + } |
| 86 | + // Fallback to JSON for complex cases |
| 87 | + try { |
| 88 | + return JSON.stringify(args); |
| 89 | + } catch { |
| 90 | + // If circular reference or non-serializable, use simple toString |
| 91 | + return args.map(String).join("|"); |
| 92 | + } |
| 93 | + }); |
| 94 | + |
| 95 | + return ((...args: Parameters<T>): ReturnType<T> => { |
| 96 | + const key = generateKey(...args); |
| 97 | + |
| 98 | + // Check cache hit |
| 99 | + if (cache.has(key)) { |
| 100 | + // Move to end (most recently used) by deleting and re-adding |
| 101 | + const cached = cache.get(key); |
| 102 | + cache.delete(key); |
| 103 | + cache.set(key, cached); |
| 104 | + return cached; |
| 105 | + } |
| 106 | + |
| 107 | + // Compute result |
| 108 | + const result = fn(...args); |
| 109 | + |
| 110 | + // Check cache size limit |
| 111 | + if (cache.size >= maxSize) { |
| 112 | + // Remove least recently used (first item) |
| 113 | + const firstKey = cache.keys().next().value; |
| 114 | + if (firstKey !== undefined) { |
| 115 | + cache.delete(firstKey); |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + // Store in cache |
| 120 | + cache.set(key, result); |
| 121 | + return result; |
| 122 | + }) as T; |
| 123 | +} |
0 commit comments