### Example: Retrieving and Logging Stats (TypeScript) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Demonstrates how to start collecting statistics, memoize a function with a stats name, trigger calls, retrieve the stats using getStats, and log the results. Ensure startCollectingStats() is called before memoizing functions if you want to track them globally. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const memoized = memoize(fn, { statsName: 'myFunc' }); memoized(1); memoized(1); memoized(2); const stats = getStats('myFunc'); console.log(stats); // { calls: 3, hits: 1, name: 'myFunc', usage: '33.3333%' } ``` -------------------------------- ### Collect and Get Memoization Statistics Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Demonstrates how to start collecting statistics, memoize functions with stats names, and retrieve the collected data. It's recommended not to use stats collection in production due to a minor performance impact. ```typescript import { getStats, memoize, startCollectingStats } from 'memoize'; startCollectingStats(); const fn = (one: string, two: string) => [one, two]; const foo = memoize((one: string, two: string) => [one, two], { statsName: 'foo', }); const bar = memoize((one: string, two: string) => `${one} ${two}`, { statsName: 'bar', }); // this will have no stats collected const baz = memoize((one: string, two: string) => ({ one, two })); foo('one', 'two'); bar('one', 'two'); foo('one', 'two'); baz('one', 'two'); console.log(getStats('foo')); /* { "calls": 2, "hits": 1, "name": "foo", "usage": "50.000000%" } */ console.log(getStats()); /* { "calls": 3, "hits": 1, "profiles: { foo: { "calls": 2, "hits": 1, "name": "foo", "usage": "50.000000%" }, "bar": { "calls": 1, "hits": 0, "name: "bar", "usage": "0.000000%" } }, "usage": "33.333333%" } */ ``` -------------------------------- ### s (start collecting) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Starts collecting stats for this profile by registering cache event listeners. This method is called automatically under specific conditions. ```APIDOC ## s (start collecting) ### Description Starts collecting stats for this profile by registering cache event listeners. Called automatically when: 1. `startCollectingStats()` is called globally and this manager already exists 2. This manager is created and stats are already being collected ### Method `s(): void` ### Behavior - Registers listeners for `'add'` and `'hit'` cache events - `'add'` event: Increments the call count - `'hit'` event: Increments both call count and hit count - Stores a function that removes these listeners in `this.d` for later cleanup ### Internal Listeners ```typescript const onAdd = () => { ++this.p.c; // Increment calls only }; const onHit = () => { ++this.p.c; // Increment calls ++this.p.h; // Increment hits }; ``` ### Note The first call to the function (cache miss, hence `'add'` event) counts as a call but not a hit. Subsequent calls with the same arguments (cache hit, hence `'hit'` event) count as both a call and a hit. ``` -------------------------------- ### Implement IsKeyEqual Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `isKeyEqual` to consider keys equal if their first argument is the same. ```typescript const memoized = memoize(fn, { isKeyEqual: (cached, next) => { // Consider keys equal if first arg is equal return cached[0] === next[0]; } }); ``` -------------------------------- ### Usage Example for CacheEntry Iteration Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Shows how to access all cache entries from a snapshot and iterate through them, logging each key-value pair. Assumes `memoized.cache.snapshot.entries` is available. ```typescript const entries = memoized.cache.snapshot.entries; entries.forEach(([key, value]) => { console.log(`Key: ${JSON.stringify(key)}, Value: ${value}`); }); ``` -------------------------------- ### Implement ForceUpdate Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `forceUpdate` to bypass cache after 5 seconds. Ensure `lastUpdate` is managed appropriately. ```typescript let lastUpdate = Date.now(); const memoized = memoize(expensiveFn, { forceUpdate: (args) => { const now = Date.now(); if (lastUpdate + 5000 < now) { lastUpdate = now; return true; // Force update after 5 seconds } return false; } }); ``` -------------------------------- ### Start Stats Collection Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Activates statistics collection for all memoized functions. New managers automatically start collecting stats after this call. ```typescript import { memoize, startCollectingStats } from 'micro-memoize'; startCollectingStats(); const fn1 = memoize((x) => x * 2, { statsName: 'fn1' }); const fn2 = memoize((x) => x + 1, { statsName: 'fn2' }); fn1(5); // Stats collected fn2(5); // Stats collected ``` -------------------------------- ### Example Usage of Key Type Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Illustrates how the `Key` type corresponds to the arguments passed to a memoized function, forming the basis for cache lookups. ```typescript const memoized = memoize((a: number, b: string) => `${a}${b}`); // The key for memoized(1, 'hello') is [1, 'hello'] ``` -------------------------------- ### Implement Serializer Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `serialize` using `JSON.stringify` to convert the arguments array into a string. ```typescript const memoized = memoize(fn, { serialize: (args) => [JSON.stringify(args)] }); ``` -------------------------------- ### Example Usage of TransformKey in Memoization Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Demonstrates how to use the `transformKey` option within the `memoize` function to customize cache key generation based on function arguments. ```typescript const memoized = memoize(fn, { transformKey: (args) => { // Ignore function arguments, keep only serializable ones return [JSON.stringify(args[0]), args[1]]; } }); ``` -------------------------------- ### Example: Resetting Stats Counters (TypeScript) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Shows how to reset the statistics counters for a memoized function. After resetting, the call and hit counts return to zero. This example verifies the reset by checking the 'calls' property before and after calling the reset method. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const memoized = memoize(fn, { statsName: 'myFunc' }); memoized(1); memoized(1); console.log(getStats('myFunc').calls); // 2 memoized.statsManager?.r(); console.log(getStats('myFunc').calls); // 0 ``` -------------------------------- ### Start Collecting Statistics (TypeScript) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Starts collecting statistics for memoized functions by registering cache event listeners. This method is called automatically when global stats collection is initiated or when a manager is created while collection is already active. It increments call and hit counts based on 'add' and 'hit' events. ```typescript s(): void ``` -------------------------------- ### Listen for Cache 'add' Events Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/CacheEventEmitter.md Subscribe to the 'add' event to be notified when a new entry is added to the cache. This example logs the key of the added entry. ```typescript memoized.cache.on('add', (event) => { console.log(`Added to cache: ${JSON.stringify(event.key)}`); }); ``` -------------------------------- ### Basic Memoization Example Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md Demonstrates basic memoization. The function's output is cached, and subsequent calls with the same arguments return the cached result without re-execution. ```typescript import { memoize } from 'micro-memoize'; const expensiveFn = (x: number, y: number) => { console.log(`Computing ${x} + ${y}`); return x + y; }; const memoized = memoize(expensiveFn); console.log(memoized(1, 2)); // Computing 1 + 2, result: 3 console.log(memoized(1, 2)); // result: 3 (from cache, no log) console.log(memoized(2, 3)); // Computing 2 + 3, result: 5 ``` -------------------------------- ### Usage Example for CacheSnapshot Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Demonstrates how to access and use a cache snapshot to log the number of cached entries and iterate through keys and their corresponding values. Assumes `memoized` is an instance of a memoized function. ```typescript const snap = memoized.cache.snapshot; console.log(`Cached ${snap.size} entries`); snap.keys.forEach((key, i) => { console.log(`${JSON.stringify(key)}: ${snap.values[i]}`); }); ``` -------------------------------- ### Async Memoization Example Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md Demonstrates memoizing an asynchronous function. The `async: true` option ensures that promises are cached and returned correctly for subsequent calls. ```typescript import { memoize } from 'micro-memoize'; const fetchData = async (id: number) => { const response = await fetch(`/api/data/${id}`); return response.json(); }; const memoized = memoize(fetchData, { async: true }); const result = await memoized(1); // Fetches data const cached = await memoized(1); // Returns cached promise ``` -------------------------------- ### Implement GetExpires Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `expires` to set cache duration based on content premium status. Premium content is cached for 10 minutes, non-premium for 1 minute. ```typescript const memoized = memoize(fetchData, { expires: (key, value) => { // Cache longer for premium content return value.premium ? 600000 : 60000; } }); ``` -------------------------------- ### Start Collecting Memoization Statistics Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Activates the collection of statistics for memoized functions that have a `statsName` option defined. ```typescript startCollectingStats(); s; ``` -------------------------------- ### Implement IsKeyItemEqual Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `isKeyItemEqual` for shallow object equality. It checks the number of keys for objects and uses strict equality otherwise. ```typescript const memoized = memoize(fn, { isKeyItemEqual: (cached, next, index) => { // Shallow equality for objects if (typeof cached === 'object' && typeof next === 'object') { return Object.keys(cached || {}).length === Object.keys(next || {}).length; } return cached === next; } }); ``` -------------------------------- ### Memoized Function Usage Example Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Shows how to access properties of a memoized function, such as its original function reference (`.fn`) and memoization options (`.options`). ```typescript const fn = (x: number) => x * 2; const memoized = memoize(fn); const original: typeof fn = memoized.fn; const stats = memoized.options.statsName; ``` -------------------------------- ### Example Usage of Cache Event Listener Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Demonstrates how to attach an event listener to a memoized function's cache to react to specific events, such as an entry being added. ```typescript const memoized = memoize(fn); const addListener: CacheEventListener<'add', typeof fn> = (event) => { console.log('Added:', event.key); }; memoized.cache.on('add', addListener); ``` -------------------------------- ### Memoize Regular Function Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md Memoize a standard JavaScript function using default options. This is the simplest way to start using memoization. ```typescript any>(fn: Fn): Memoized ``` -------------------------------- ### ProfileStats Usage Example Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Demonstrates how to retrieve and display statistics for a memoized function using its profile name. Ensure the memoized function has stats collection enabled. ```typescript const stats = getStats('myFunction'); console.log(`${stats.name}: ${stats.usage} hit rate (${stats.hits}/${stats.calls})`); ``` -------------------------------- ### Implement ShouldPersist Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `shouldPersist` to prevent expiration for static content. Cache entries with `isStatic: true` will never expire. ```typescript const memoized = memoize(fn, { expires: { after: 5000, shouldPersist: (key, value) => { // Never expire static content return value.isStatic === true; } } }); ``` -------------------------------- ### StatsManager.s() Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Starts collecting statistics by setting up necessary listeners on the associated cache. This method is typically called internally when stats collection is enabled globally. ```APIDOC ## StatsManager.s() ### Description Starts collecting statistics by setting up necessary listeners on the associated cache. This method is typically called internally when stats collection is enabled globally. ### Method `s()` ### Parameters None ### Returns None ``` -------------------------------- ### Get Profile Statistics (TypeScript) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Computes and returns the metrics for a profile's statistics. Use this to inspect cache performance. The 'usage' is calculated as (hits / calls) * 100, formatted to 4 decimal places, or '0.0000%' if no calls have been made. ```typescript m(): ProfileStats ``` -------------------------------- ### Listen for Cache 'update' Events Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/CacheEventEmitter.md Subscribe to the 'update' event to be notified when an existing cache entry's position is updated, or when a promise resolves for an async function. This example logs the key of the updated entry. ```typescript memoized.cache.on('update', (event) => { console.log(`Updated cache entry: ${JSON.stringify(event.key)}`); }); ``` -------------------------------- ### Get Profile Stats with Cache Hits Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Demonstrates retrieving statistics for a profile after several calls, including cache hits. This helps visualize the effectiveness of memoization. Ensure stats collection is active. ```typescript startCollectingStats(); const fn = memoize(expensive, { statsName: 'myFunc' }); // Multiple calls with repeated arguments fn(1); // Cache miss (add event) fn(1); // Cache hit fn(1); // Cache hit fn(2); // Cache miss (add event) fn(2); // Cache hit fn(3); // Cache miss (add event) const stats = getStats('myFunc'); console.log(stats); /* { calls: 6, hits: 3, name: 'myFunc', usage: '50.0000%' } */ ``` -------------------------------- ### Basic Memoization with Options Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/configuration.md Demonstrates how to apply configuration options when creating a memoized function. Sets async handling, max cache size, and item equality comparison. ```typescript const memoized = memoize(fn, { async: true, maxSize: 10, isKeyItemEqual: 'deep' }); ``` -------------------------------- ### Cache.size Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Gets the current number of items in the cache. ```APIDOC ## Cache.size ### Description Gets the current number of items in the cache. ### Returns (number) - The number of items currently stored in the cache. ``` -------------------------------- ### ExpirationManager.size Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/ExpirationManager.md Gets the current number of cache entries being managed for expiration. ```APIDOC ## ExpirationManager.size ### Description Gets the current number of cache entries being managed for expiration. ### Method GET ### Endpoint ExpirationManager.size ### Parameters None ### Response #### Success Response (200) - **size** (number) - The number of cache entries currently managed. ``` -------------------------------- ### Get Cache Snapshot Type Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Defines the structure of a cache snapshot, useful for debugging. ```typescript type CacheSnapshot = { entries: Array<[Key, ReturnType]>; keys: Key[]; size: number; values: Array>; }; ``` -------------------------------- ### Source Code Organization Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/README.md Illustrates the directory structure of the micro-memoize project, showing the main files and their purposes. ```tree src/ ├── index.ts # Main export and memoize function ├── Cache.ts # Cache class implementation ├── CacheEventEmitter.ts # Event emitter for cache changes ├── ExpirationManager.ts # Expiration/TTL management ├── stats.ts # Statistics collection ├── internalTypes.ts # Type definitions ├── maxArgs.ts # MaxArgs transformer utility ├── serialize.ts # Serialization utilities └── utils.ts # Helper functions ``` -------------------------------- ### Option Processing Pipeline Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/README.md Visualizes the sequence of key transformation options applied to function arguments to generate the final cache key. This pipeline includes optional steps like transformKey, maxArgs, and serialize. ```text Arguments | v [transformKey] (if provided) | v [maxArgs] (if provided) | v [serialize] (if provided) | v Final Cache Key ``` -------------------------------- ### Start Collecting Statistics Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Activates statistics collection for all memoized functions that have a 'statsName' option configured. This function sets the global stats collection flag to active and registers event listeners on existing StatsManager instances. New managers created after this call will also automatically start collecting stats. It has no effect if stats collection is already active. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; // Before any memoized functions are created startCollectingStats(); const add = memoize((a, b) => a + b, { statsName: 'add' }); const multiply = memoize((a, b) => a * b, { statsName: 'multiply' }); add(1, 2); add(1, 2); // Cache hit multiply(3, 4); // Stats are now being collected console.log(getStats('add').hits); // 1 ``` -------------------------------- ### startCollectingStats() Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Initiates the collection of statistics for memoized functions that have a `statsName` option defined. ```APIDOC ## startCollectingStats() ### Description Start collecting statistics on `memoize`d functions with defined `statsName` options. ### Usage ```ts startCollectingStats(); s; ``` ``` -------------------------------- ### Get Cache Size Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Retrieves the current number of entries stored in the cache. Useful for monitoring cache usage. ```typescript const memoized = memoize(fn, { maxSize: 3 }); memoized(1); memoized(2); console.log(memoized.cache.size); // 2 ``` -------------------------------- ### Get Global Stats for All Profiles Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Retrieves global statistics for all memoized functions. Returns undefined if stats collection is not active. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const add = memoize((a, b) => a + b, { statsName: 'add' }); const multiply = memoize((a, b) => a * b, { statsName: 'multiply' }); add(1, 2); add(1, 2); multiply(3, 4); console.log(getStats()); /* { calls: 3, hits: 1, profiles: { add: { calls: 2, hits: 1, name: 'add', usage: '50.0000%' }, multiply: { calls: 1, hits: 0, name: 'multiply', usage: '0.0000%' } }, usage: '33.3333%' } */ ``` -------------------------------- ### Get Value from Cache Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Retrieve a value from the cache using an array of arguments as the key. Returns `undefined` if the key is not found. ```typescript const memoized = memoize((one: string, two: string) => [one, two); memoized('one', 'two'); console.log(memoized.cache.get(['one', 'two'])); // ["one","two"] console.log(memoized.cache.get(['two', 'three'])); // undefined ``` -------------------------------- ### Cache Constructor Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Initializes a new instance of the Cache class with specified options. ```APIDOC ## new Cache(options: Options) ### Description Initializes a new instance of the Cache class with specified options. ### Parameters #### Parameters - **options** (Options) - Required - Configuration object for the cache. See [Configuration Reference](../configuration.md) ``` -------------------------------- ### Monitor Cache Effectiveness Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Tracks the cache efficiency of a memoized function by collecting and analyzing statistics. Requires starting statistics collection. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const fibonacci = memoize(fib, { statsName: 'fibonacci' }); // Run algorithm for (let i = 0; i < 100; i++) { fibonacci(30); } const stats = getStats('fibonacci'); console.log(`Cache efficiency: ${stats.usage}`); ``` -------------------------------- ### on Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Registers an event listener for cache change events. Supported event types are 'add', 'delete', 'hit', and 'update'. ```APIDOC ## on ### Description Registers an event listener for cache change events. Supported event types are `'add'`, `'delete'`, `'hit'`, and `'update'`. ### Method `on(type: Type, listener: CacheEventListener): void` ### Parameters #### Path Parameters - `type` ('add' | 'delete' | 'hit' | 'update') - Required - The cache event type to listen for. - `listener` (CacheEventListener) - Required - Callback function to invoke when the event occurs. ### Example ```typescript const memoized = memoize((x: number) => x * 2, { maxSize: 2 }); memoized.cache.on('add', (event) => { console.log(`Added to cache: ${JSON.stringify(event.key)}`); }); memoized.cache.on('delete', (event) => { console.log(`Deleted from cache: ${JSON.stringify(event.key)} (${event.reason})`); }); memoized(1); // Added to cache: [1] memoized(2); // Added to cache: [2] memoized(3); // Added to cache: [3] // Deleted from cache: [1] (evicted) ``` ``` -------------------------------- ### Get Stats for an Individual Profile Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Retrieves statistics for a specific memoized function profile. Returns undefined if stats collection is not active. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const add = memoize((a, b) => a + b, { statsName: 'add' }); add(1, 2); add(1, 2); // Cache hit console.log(getStats('add')); /* { calls: 2, hits: 1, name: 'add', usage: '50.0000%' } */ ``` -------------------------------- ### Import Main Export (TypeScript) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/README.md Import the primary memoize function from the micro-memoize library. ```typescript import { memoize } from 'micro-memoize'; ``` -------------------------------- ### Compare Multiple Memoization Strategies Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Compares the performance and cache efficiency of different memoization strategies by assigning unique stats names and analyzing their usage. ```typescript startCollectingStats(); const strategy1 = memoize(fn, { statsName: 'strategy1', maxSize: 5 }); const strategy2 = memoize(fn, { statsName: 'strategy2', maxSize: 20 }); // Run tests... const s1 = getStats('strategy1'); const s2 = getStats('strategy2'); console.log(`Strategy 1 efficiency: ${s1.usage}`); console.log(`Strategy 2 efficiency: ${s2.usage}`); ``` -------------------------------- ### Implement ShouldRemoveOnExpire Logic Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md Example of implementing `shouldRemove` to conditionally remove expired entries. Entries are removed only if they haven't been updated in the last hour. ```typescript const memoized = memoize(fn, { expires: { after: 5000, shouldRemove: (key, value, time) => { // Only remove if not updated in the last hour return Date.now() - value.lastUpdate > 3600000; } } }); ``` -------------------------------- ### Import micro-memoize (CommonJS) Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Import the memoize function using CommonJS syntax. ```javascript const { memoize } = require('micro-memoize'); ``` -------------------------------- ### Basic Usage of memoize Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Demonstrates basic memoization of a function. Subsequent calls with the same arguments will retrieve the result from the cache. ```typescript const toObject = (one: string, two: string) => ({ one, two }); const memoized = memoize(toObject); console.log(memoized('one', 'two')); console.log(memoized('one', 'two')); // pulled from cache ``` -------------------------------- ### Get Expiration Manager Size Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/ExpirationManager.md Retrieves the number of active expiration timers managed by the ExpirationManager. Useful for monitoring pending cache expirations. ```typescript const memoized = memoize(fn, { expires: 5000 }); memoized(1); memoized(2); console.log(memoized.expirationManager?.size); // 2 ``` -------------------------------- ### Get Specific or Global Memoization Statistics Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Demonstrates retrieving statistics for a named memoized function or all collected statistics. Ensure `startCollectingStats()` has been called. ```typescript startCollectingStats(); const fn = (one: string, two: string) => [one, two]; const memoized = memoize(fn); const otherFn = (one: string[]) => one.slice(0, 1); const otherMemoized = memoize(otherFn, { statsName: 'otherMemoized' }); memoized('one', 'two'); memoized('one', 'two'); otherMemoized(['three']); getStats('otherMemoized'); /* { "calls": 1, "hits": 0, "name": "otherMemoized", "usage": "0.000000%" } */ getStats(); /* { "calls": 3, "hits": 1, "profiles": { "otherMemoized": { "calls": 1, "hits": 0, "name": "otherMemoized", "usage": "0.000000%" } }, "usage": "33.3333%" } */ ``` -------------------------------- ### Cache.on Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Adds an event listener to the cache. ```APIDOC ## Cache.on(type: Type, listener: CacheEventListener) ### Description Adds an event listener to the cache. ### Parameters #### Path Parameters - **type** (Type) - Required - The type of cache event to listen for. - **listener** (CacheEventListener) - Required - The listener function to add. ``` -------------------------------- ### Option Processing Order Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/configuration.md Illustrates the order in which key transformation options are applied: `transformKey`, `maxArgs`, and `serialize`. Ensure options are configured in this sequence for predictable key generation. ```typescript const memoized = memoize(fn, { transformKey: (args) => [args[0].id, args[1]], // Step 1 maxArgs: 1, // Step 2 serialize: (key) => [JSON.stringify(key)] // Step 3 }); ``` -------------------------------- ### A/B Testing Strategies with Memoized Functions Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Implement A/B testing by creating multiple memoized functions with distinct stats names. This allows for comparing the performance or effectiveness of different strategies. ```typescript startCollectingStats(); const strategy1 = memoize(fn, { statsName: 'strategy1', maxSize: 5 }); const strategy2 = memoize(fn, { statsName: 'strategy2', maxSize: 20 }); // Test both... const stats1 = getStats('strategy1'); const stats2 = getStats('strategy2'); console.log(`Strategy 1: ${stats1.usage}`); console.log(`Strategy 2: ${stats2.usage}`); ``` -------------------------------- ### set Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Manually adds or updates a cache entry with a specified key, value, and an optional reason. ```APIDOC ## set ### Description Manually adds or updates a cache entry. ### Method void ### Parameters #### Path Parameters - `key` (Parameters) - Required - Array of arguments to use as the cache key - `value` (ReturnType) - Required - The value to cache - `reason` (string) - Optional - The reason for setting, passed to event listeners. Defaults to 'explicit set'. ### Example ```typescript const memoized = memoize((x: number) => x * 2); memoized.cache.set([5], 10); console.log(memoized.cache.get([5])); // 10 ``` ``` -------------------------------- ### Indirect Usage of CacheEventEmitter Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/CacheEventEmitter.md Demonstrates how to use the CacheEventEmitter indirectly via the memoized function's cache property. This example subscribes to the 'add' event. ```typescript const memoized = memoize((x: number) => x * 2); // Uses CacheEventEmitter internally memoized.cache.on('add', (event) => { console.log('Cache event:', event); }); ``` -------------------------------- ### Overload 4: Memoize Regular Function with Options Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md This overload allows memoizing a regular function while providing custom configuration options. ```APIDOC ## Overload 4: Memoize Regular Function with Options ### Description Memoize a regular function with custom options. ### Signature ```typescript any, Opts extends Options>( fn: Fn, passedOptions: Opts ): Memoized ``` ``` -------------------------------- ### Get Cache Node Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md The `g` method finds an existing cache node by key using the provided equality comparison function. This is an internal method. ```typescript g(key: Key): CacheNode | undefined ``` -------------------------------- ### Composition of Memoized Functions Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md Shows how to compose memoized functions. A new memoized function can be created by memoizing an already memoized function, inheriting and merging options. ```typescript import { memoize } from 'micro-memoize'; const original = (x: number) => x * 2; const memoized1 = memoize(original, { maxSize: 5 }); const memoized2 = memoize(memoized1, { async: true }); // memoized2 is now memoized with both maxSize: 5 and async: true console.log(memoized2.options); // { maxSize: 5, async: true } ``` -------------------------------- ### memoized.cache.get(args) Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Retrieves a value from the cache using the provided arguments as the key. Returns `undefined` if no matching entry is found. ```APIDOC ## memoized.cache.get(args) ### Description Returns the value in cache if the key based on `args` matches, else returns `undefined`. `args` should be an `Array` of values, meant to reflect the arguments passed to the method. ### Method `get` ### Parameters #### Path Parameters - **args** (Array) - Required - An array of values to use as the cache key. ### Response #### Success Response (200) - **value** (any) - The cached value, or `undefined` if not found. ### Request Example ```ts const memoized = memoize((one: string, two: string) => [one, two); memoized('one', 'two'); console.log(memoized.cache.get(['one', 'two'])); // ["one","two"] console.log(memoized.cache.get(['two', 'three'])); // undefined ``` ``` -------------------------------- ### Get Global Statistics Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Retrieves aggregated statistics across all memoized function profiles. This is useful for understanding overall performance. Ensure stats collection is active. ```typescript startCollectingStats(); const add = memoize((a, b) => a + b, { statsName: 'add' }); const multiply = memoize((a, b) => a * b, { statsName: 'multiply' }); const divide = memoize((a, b) => a / b, { statsName: 'divide' }); // Use the functions for (let i = 0; i < 10; i++) { add(i, i); multiply(i, i); divide(100, i || 1); } const globalStats = getStats(); console.log(globalStats); /* { calls: 30, hits: 0, profiles: { add: { calls: 10, hits: 0, name: 'add', usage: '0.0000%' }, multiply: { calls: 10, hits: 0, name: 'multiply', usage: '0.0000%' }, divide: { calls: 10, hits: 0, name: 'divide', usage: '0.0000%' } }, usage: '0.0000%' } */ ``` -------------------------------- ### memoized.options Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Access the options that were passed when creating the memoized method. ```APIDOC ## memoized.options ### Description The [`options`](#options) passed when creating the memoized method. ``` -------------------------------- ### get Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Retrieves the cached value for the given arguments without triggering a cache hit event. Returns the cached value or `undefined` if not found. An optional reason can be provided. ```APIDOC ## get ### Description Retrieves the cached value for the given arguments without triggering a cache hit event (useful for introspection). Returns the cached value or `undefined` if not found. An optional reason can be provided. ### Method `get(args: Parameters, reason?: string): ReturnType | undefined` ### Parameters #### Path Parameters - `args` (Parameters) - Required - Array of arguments matching the cache key. - `reason` (string) - Optional - The reason for the get, passed to event listeners if entry exists. Defaults to `'explicit get'`. ### Returns `ReturnType | undefined` - The cached value, or `undefined` if not found. ### Example ```typescript const memoized = memoize((x: number) => x * 2); memoized(5); console.log(memoized.cache.get([5])); // 10 console.log(memoized.cache.get([10])); // undefined ``` ``` -------------------------------- ### m (metrics) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/StatsManager.md Computes and returns the metrics for this profile's statistics, including total calls, cache hits, and cache efficiency. ```APIDOC ## m (metrics) ### Description Computes and returns the metrics for this profile's statistics. ### Method `m(): ProfileStats` ### Returns `ProfileStats` object with: - `calls`: Total number of function calls (including cache hits) - `hits`: Number of cache hits - `name`: The stats name - `usage`: Cache efficiency as a percentage string (e.g., `"66.6667%"`) ### Calculation - `usage = (hits / calls) * 100` formatted to 4 decimal places - If `calls === 0`, usage is `"0.0000%"` ### Example ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const memoized = memoize(fn, { statsName: 'myFunc' }); memoized(1); memoized(1); memoized(2); const stats = getStats('myFunc'); console.log(stats); // { calls: 3, hits: 1, name: 'myFunc', usage: '33.3333%' } ``` ``` -------------------------------- ### Get Cache Snapshot Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Obtains an immutable snapshot of the cache's current state, including entries, keys, and values. Useful for debugging as the cache mutates in place. ```typescript const memoized = memoize((x: number) => x * 2); memoized(5); memoized(10); const snap = memoized.cache.snapshot; console.log(snap.keys); // [[5], [10]] console.log(snap.values); // [10, 20] console.log(snap.size); // 2 ``` -------------------------------- ### Composing Memoized Functions Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Shows how to compose multiple memoized functions with different options. Each new memoized function inherits from the previous one, applying its own options. ```typescript const toObject = (one: string, two: string) => ({ one, two }); const memoized = memoize(toObject); const withUpToFive = memoize(memoized, { maxSize: 5 }); // { maxSize: 5 } const withAsync = memoize(withUpToFive, { async: true }); // { async: true, maxSize: 5 } const withCustomEquals = memoize(withAsync, { isEqual: deepEqual }); // { async: true, maxSize: 5, isEqual: deepEqual } ``` -------------------------------- ### Get Cached Value Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/Cache.md Retrieves a cached value for given arguments without triggering a cache hit event. Useful for inspecting cache contents. Returns `undefined` if the entry does not exist. ```typescript const memoized = memoize((x: number) => x * 2); memoized(5); console.log(memoized.cache.get([5])); // 10 console.log(memoized.cache.get([10])); // undefined ``` -------------------------------- ### Monitor Cache Effectiveness with StatsManager Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Use this pattern to monitor the cache hit rate of memoized functions. Ensure stats collection is started before creating memoized functions and retrieve stats to check usage. ```typescript startCollectingStats(); const computeExpensive = memoize(expensiveCalc, { statsName: 'expensive', maxSize: 100 }); // Run your computations... const stats = getStats('expensive'); if (stats.usage < '50.0000%') { console.warn('Low cache hit rate - consider increasing maxSize'); } ``` -------------------------------- ### Custom Key Comparison: Deep and Shallow Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/memoize.md Illustrates using custom key comparison strategies. 'deep' performs a deep comparison of arguments, while 'shallow' performs a shallow comparison. This is useful for memoizing functions that accept complex arguments like objects. ```typescript import { memoize } from 'micro-memoize'; const process = (obj: { a: number; b: number }) => obj.a + obj.b; // Deep comparison of arguments const deepMemoized = memoize(process, { isKeyItemEqual: 'deep' }); const result1 = deepMemoized({ a: 1, b: 2 }); const result2 = deepMemoized({ a: 1, b: 2 }); // Same object structure, cached // Shallow comparison const shallowMemoized = memoize(process, { isKeyItemEqual: 'shallow' }); ``` -------------------------------- ### Enable Key Serialization Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Serializes function arguments into a string to use as the cache key. A custom serializer function can also be provided. ```typescript const fn = (mutableObject: { one: Record }) => mutableObject.property; const serializedMemoized = memoize(fn, { serialize: true }); const customSerializedMemoized = memoize(fn, { serialize: (args) => [JSON.stringify(args[0])], }); ``` -------------------------------- ### Define Memoization Options (Custom Key Item Equality) Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/types.md OptionsKeyItemEqual is used when specifying how individual arguments should be compared for cache key equality. It allows for 'deep', 'shallow', or a custom comparison function. ```typescript interface OptionsKeyItemEqual any> extends OptionsBase { isKeyEqual?: never; isKeyItemEqual?: 'deep' | 'shallow' | IsKeyItemEqual; } ``` -------------------------------- ### Get Stats for a Single Profile Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Retrieves statistics for a specific memoized function profile using its statsName. Ensure stats collection is active and the profile name is correctly provided. Returns undefined if stats collection is inactive. ```typescript import { memoize, startCollectingStats, getStats } from 'micro-memoize'; startCollectingStats(); const fibonacci = memoize((n) => { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }, { statsName: 'fibonacci' }); fibonacci(10); const stats = getStats('fibonacci'); console.log(stats); /* { calls: 177, hits: 165, name: 'fibonacci', usage: '93.2203%' } */ console.log(`Cache hit rate: ${stats.usage}`); ``` -------------------------------- ### Cache Structure Diagram Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/README.md Illustrates the internal doubly-linked list structure used for LRU cache management. New or accessed entries move to the head, and the tail is evicted when maxSize is exceeded. ```text Most Recent -> [Entry 1] <-> [Entry 2] <-> [Entry 3] <- Least Recent ``` -------------------------------- ### Async Function Reject Handling Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/configuration.md Shows how to configure memoization for asynchronous functions. When an async function's promise rejects, the corresponding cache entry is automatically removed. ```typescript const fetchUser = async (id: number) => { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error('Failed to fetch'); return response.json(); }; const memoized = memoize(fetchUser, { async: true }); // If the promise rejects, the cache entry is automatically removed memoized(1).catch(err => { // Cache entry for [1] is now gone memoized(1); // Will call fetchUser again }); ``` -------------------------------- ### Import micro-memoize (ESM) Source: https://github.com/planttheidea/micro-memoize/blob/main/README.md Import the memoize function using ECMAScript Module syntax. ```typescript import { memoize } from 'micro-memoize'; ``` -------------------------------- ### Periodic Performance Reporting Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/statistics-functions.md Set up a recurring task to log performance metrics for all memoized functions. This helps in identifying performance bottlenecks over time. ```typescript setInterval(() => { const stats = getStats(); if (stats) { Object.entries(stats.profiles).forEach(([name, profile]) => { console.log(`${name}: ${profile.calls} calls, ${profile.usage} hit rate`); }); } }, 60000); // Every minute ``` -------------------------------- ### Registering an event listener Source: https://github.com/planttheidea/micro-memoize/blob/main/_autodocs/api-reference/CacheEventEmitter.md Use the 'a' method to add a callback function that will be invoked when a specific cache event occurs. Duplicate listeners for the same event type are automatically ignored. ```typescript a(type: Type, listener: CacheEventListener): void ``` ```typescript const emitter = new CacheEventEmitter(cache); const handler = (event) => console.log('Cache updated:', event.key); emitter.a('add', handler); emitter.a('add', handler); // Handler is not added twice ```