From 4425527c2842aa2bbdc9a06e21aed90b7b450525 Mon Sep 17 00:00:00 2001 From: Pierre Mdawar Date: Tue, 28 Jun 2022 18:04:45 +0300 Subject: [PATCH] Document the cacheId helper functions --- README.md | 43 ++++++++++++++++++++++++++++++++++++++++++- src/helpers.ts | 2 +- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f45f3b5..a93bd36 100644 --- a/README.md +++ b/README.md @@ -158,7 +158,7 @@ Required `cache` object methods: ## Cache ID -By default the first argument of the memoized function is used as the cache ID to store the result. +By default the **first argument** of the memoized function is used as the cache ID to store the result. ```js const memoized = memoize(expensiveFunction); @@ -222,6 +222,47 @@ memoized(/(.*)/); // Cached memoized(/(.*)/); // Cached ``` +### Cache ID Helpers + +The module `memoize-utils/helpers` provides some commonly used `cacheId` functions: + +- `all`: Get an ID from all the arguments casted to a string and then joined together. +- `json`: Get a JSON string ID from the arguments (`JSON.stringify(args)`). +- `anyOrder`: Get the same ID from a set of arguments passed in any order. + +Usage: + +```js +import { all, json, anyOrder } from 'memoize-utils/helpers'; + +// Use all the arguments as an ID +// Note: does not work with objects (Arguments are casted to strings) +// but it works with `RegExp` objects +memoize(fn, { cacheId: all }); + +// Use all the arguments as an ID including objects +// Note: does not work with `RegExp` objects +memoize(fn, { cacheId: json }); + +// Use all the arguments as an ID but in any order +// Note: does not work with objects (Arguments are casted to strings) +memoize(fn, { cacheId: anyOrder }); +``` + +You can create your own `memoize` wrapper function using a custom cache ID: + +```js +import { memoize } from 'memoize-utils'; +import { anyOrder } from 'memoize-utils/helpers'; + +export function memoizeAnyOrder(fn, options) { + return memoize(fn, { cacheId: anyOrder, ...options }); +} + +// Memoize functions using all of the arguments as a cache ID in any order +const memoized = memoizeAnyOrder(fn); +``` + ## Rejected Promises By default rejected promises are not cached, this is done to have the same functionality for synchronous functions when throwing errors. diff --git a/src/helpers.ts b/src/helpers.ts index 03c90ca..44175ec 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -23,7 +23,7 @@ export function json(...args: readonly any[]): string { } /** - * Get the same ID from a set of arguments no matter the order they're passed in. + * Get the same ID from a set of arguments passed in any order. * * The passed arguments are sorted and then casted to a string and then joined together. *