`moize` is a [consistently blazing fast](#benchmarks) memoization library for JavaScript. It handles multiple parameters (including default values) without any additional configuration, and offers a large number of options to satisfy any number of potential use-cases.
- [Importing](#importing)
- [ESM in browsers](#esm-in-browsers)
- [ESM in NodeJS](#esm-in-nodejs)
- [CommonJS](#commonjs)
- [Usage](#usage)
- [Configuration options](#configuration-options)
- [isDeepEqual](#isdeepequal)
- [isPromise](#ispromise)
- [isReact](#isreact)
- [isSerialized](#isserialized)
- [isShallowEqual](#isshallowequal)
- [matchesArg](#matchesarg)
- [matchesKey](#matcheskey)
- [maxAge](#maxage)
- [maxArgs](#maxargs)
- [maxSize](#maxsize)
- [onCacheAdd](#oncacheadd)
- [onCacheChange](#oncachechange)
- [onCacheHit](#oncachehit)
- [onExpire](#onexpire)
- [profileName](#profilename)
- [serializer](#serializer)
- [transformArgs](#transformargs)
- [updateCacheForKey](#updatecacheforkey)
- [updateExpire](#updateexpire)
- [Usage with shortcut methods](#usage-with-shortcut-methods)
All parameter types are supported, including circular objects, functions, etc. There are also a number of [shortcut methods](#usage-with-shortcut-methods) to memoize for unique use-cases.
# Configuration options
`moize` optionally accepts an object of options as either the second parameter or as the first step in a curried function:
```ts
// inline
moize(fn, options);
// curried
moize(options)(fn);
```
The full shape of these options:
```ts
type Options = {
// is the cache based on deep equality of each key argument
isDeepEqual: boolean;
// is the result a promise
isPromise: boolean;
// is the result a React component
isReact: boolean;
// should the parameters be serialized instead of directly referenced
isSerialized: boolean;
// is the cache based on shallow equality of each key argument
isShallowEqual: boolean;
// custom method to compare equality between two key arguments
This is also available via the shortcut method of [`moize.promise`](#moizepromise).
```ts
const memoized = -moize.promise(fn);
```
The `Promise` itself will be stored in cache, so that cached returns will always maintain the `Promise` contract. For common usage reasons, if the `Promise` is rejected, the cache entry will be deleted.
## isReact
_defaults to false_
Is the function passed a stateless functional `React` component.
This is also available via the shortcut method of [`moize.react`](#moizereact).
```ts
const MemoizedFoo = moize.react(Component);
```
The method will do a shallow equal comparison of both `props` and legacy `context` of the component based on strict equality. If you want to do a deep equals comparison, set [`isDeepEqual`](#isdeepequal) to true.
**NOTE**: This will memoize on each instance of the component passed, which is equivalent to `PureComponent` or `React.memo`. If you want to
memoize on _all_ instances (which is how this option worked prior to version 6), use the following options:
This is also available via the shortcut method of [`moize.serialize`](#moizeserialize).
```ts
const memoized = moize.serialize(fn);
```
If `serialize` is combined with either `maxArgs` or `transformArgs`, the following order is used:
1. limit by `maxArgs` (if applicable)
1. transform by `transformArgs` (if applicable)
1. serialize by `serializer`
**NOTE**: This is much slower than the default key storage, and usually the same requirements can be meet with `isDeepEqual`, so use at your discretion.
## isShallowEqual
_defaults to false_
Should shallow equality be used to compare cache each key argument.
**NOTE**: This comparison is used iteratively on each argument, rather than comparing the two keys as a whole. If you want to compare the key as a whole, you should use [`matchesKey`](#matcheskey).
## matchesKey
Custom method used to compare equality of keys for cache purposes by comparing the entire key.
**NOTE**: This comparison uses the two keys as a whole, which is usually less performant than the `matchArg` comparison used iteratively on each argument. Generally speaking you should use the [`matchArg`](#matchesarg) option for equality comparison.
## maxAge
The maximum amount of time in milliseconds that you want a computed value to be stored in cache for this method.
```ts
const fn = (item: Record<string,any>) => item;
const MAX_AGE = 1000 * 60 * 5; // five minutes;
const memoized = moize(fn, { maxAge: MAX_AGE });
```
This is also available via the shortcut method of [`moize.maxAge`](#moizemaxage).
```ts
const memoized = moize.maxAge(MAX_AGE)(fn);
```
**TIP**: A common usage of this is in tandom with `isPromise` for AJAX calls, and in that scenario the expected behavior is usually to have the `maxAge` countdown begin upon resolution of the promise. If this is your intended use case, you should also apply the `updateExpire` option.
## maxArgs
The maximum number of arguments (starting from the first) used in creating the key for the cache.
memoize('one', 'two', 'four'); // pulls from cache, as the first two args are the same
```
This is also available via the shortcut method of [`moize.maxArgs`](#moizemaxargs).
```ts
const memoized = moize.maxArgs(2)(fn);
```
If `maxArgs` is combined with either `serialize` or `transformArgs`, the following order is used:
1. limit by `maxArgs`
1. transform by `transformArgs` (if applicable)
1. serialize by `serializer` (if applicable)
## maxSize
_defaults to 1_
The maximum number of values you want stored in cache for this method. Clearance of the cache once the `maxSize` is reached is on a [Least Recently Used](https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29) basis.
```ts
const fn = (item: string) => item;
const memoized = moize(fn, { maxSize: 5 });
```
This is also available via the shortcut method of [`moize.maxSize`](#moizemaxsize).
```ts
const memoized = moize.maxSize(5)(fn);
```
## onCacheAdd
Method to fire when an item has been added to cache. Receives the cache, options, and memoized function as a parameters.
**NOTE**: When combined with `onCacheChange`, this method will always fire first.
## onCacheChange
Method to fire when an item has been either added to cache, or existing cache was reordered based on a cache hit. Receives the cache, options, and memoized function as a parameters.
If you return `false` from this method, it will prevent the key's removal and refresh the expiration in the same vein as `updateExpire` based on `maxAge`:
**NOTE**: You must be collecting statistics for this option to provide value, as it is the identifier used for statistics collection.
## serializer
_defaults to serializeArguments in utils.js_
Method used in place of the internal serializer when serializing the parameters for cache key comparison. The function accepts a single argument, the `Array` of `args`, and must also return an `Array`.
**NOTE**: You must set [`isSerialized`](#isserialized) for this option to take effect.
## transformArgs
Transform the arguments passed before it is used as a key. The function accepts a single argument, the `Array` of `args`, and must also return an `Array`.
When a `maxAge` is set, clear the scheduled expiration of the key when that key is retrieved, setting a new expiration based on the most recent retrieval from cache.
**NOTE**: You must be collecting statistics for this option to provide value, as it is the identifier used for statistics collection.
## moize.promise
Pre-applies the [`isPromise`](#ispromise) and [`updateExpire`](#updateexpire) options. The `updateExpire` option does nothing if [`maxAge`](#maxage) is not also applied, but ensures that the expiration begins at the resolution of the promise rather than the instantiation of it.
**NOTE**: If you do not want the promise to update its expiration when the cache is hit, then you should use the `isPromise` option directly instead.
## moize.react
Pre-applies the [`isReact`](#isreact)) option for memoizing functional components in [React](https://github.com/facebook/react). `Key` comparisons are based on a shallow equal comparison of both props and legacy context.
```tsx
import moize from 'moize';
type Props = {
one: string;
two: number;
};
const Component = ({ one, two }: Props) => (
<div>
{one} {two}
</div>
);
export default moize.react(Component);
```
**NOTE**: This method will not operate with components made via the `class` instantiation, as they do not offer the same [referential transparency](https://en.wikipedia.org/wiki/Referential_transparency).
## moize.serialize
Pre-applies the [`isSerialized`](#isSerialized) option.
Sum of {first} and {second} is {sum}. Sum of {object.a} and{' '}
{object.b} is {deepSum}.
</div>
);
}
```
Naturally you can tweak as needed for your project (default options, option-specific hooks, etc).
**NOTE**: This is very similar to [`useCallback`](https://reactjs.org/docs/hooks-reference.html#usecallback) built-in hook, with two main differences:
- There is a third parameter passed (the [`options`](#configuration-options) passed to `moize`)
- The second argument array is the list of arguments passed to the memoized function
In both `useCallback` and `useMemo`, the array is a list of _dependencies_ which determine whether the funciton is called. These can be different than the arguments, although in general practice they are equivalent. The decision to use them directly was both for this common use-case reasons, but also because the implementation complexity would have increased substantially if not.
# Composition
Starting with version `2.3.0`, you can compose `moize` methods. This will create a new memoized method with the original function that shallowly merges the options of the two setups. Example:
**NOTE**: If collecting statistics, it is recommended to provide a custom [`profileName`](#profilename) or use [`moize.profile()`](#moizeprofile) for all memoized functions. This allows easier mapping of resulting statistics to their origin function when it has a common name or is anonymous.
## getStats([profileName])
Get the statistics for a specific function, or globally.
"fn at Object..src/utils.js (http://localhost:3000/app.js:153:68)": {
"calls": 2,
"hits": 1,
"usage": "50%"
},
"otherMoized": {
"calls": 1,
"hits": 0,
"usage": "0%"
}
},
"usage": "33.3333%"
}
*/
```
# Introspection
## isCollectingStats
Are statistics being collected on memoization usage.
```ts
moize.collectStats(true);
moize.isCollectingStats(); // true
moize.collectStats(false);
moize.isCollectingStats(); // false
```
## isMoized
Is the function passed a moized function.
```ts
const fn = () => {};
const moizedFn = moize(fn);
moize.isMoized(fn); // false
moize.isMoized(moizedFn); // true
```
# Direct cache manipulation
The cache is available on the `moize`d function as a property, and while it is not recommended to modify it directly, that option is available for edge cases.
## cache
The shape of the `cache` is as follows:
```ts
type Cache = {
keys: any[][];
size: number;
values: any[];
};
```
Regardless of how the key is transformed, it is always stored as an array (if the value returned is not an array, it is coalesced to one).
**NOTE**: The order of `keys` and `values` should always align, so be aware when manually manipulating the cache that you need to manually keep in sync any changes to those arrays.
## cacheSnapshot
The `cache` is mutated internally for performance reasons, so logging out the cache at a specific step in the workflow may not give you the information you need. As such, to help with debugging you can request the `cacheSnapshot`, which has the same shape as the `cache` but is a shallow clone of each property for persistence.
There are also convenience methods provided on the `moize`d function which allow for programmatic manipulation of the cache.
## add(key, value)
This will manually add the _value_ at _key_ in cache if _key_ does not already exist. _key_ should be an `Array` of values, meant to reflect the arguments passed to the method.
**NOTE**: This will only add `key`s that do not exist in the cache, and will do nothing if the `key` already exists. If you want to update keys that already exist, use [`update`](#updatekey-value).
## clear()
This will clear all values in the cache, resetting it to an empty state.
```ts
const memoized = moize((item: string) => item);
memoized.clear();
```
## get(key)
Returns the value in cache if the key matches, else returns `undefined`. _key_ should be an `Array` of values, meant to reflect the arguments passed to the method.
**NOTE**: You must be collecting statistics for this to be populated.
## has(key)
This will return `true` if a cache entry exists for the _key_ passed, else will return `false`. _key_ should be an `Array` of values, meant to reflect the arguments passed to the method.
**NOTE**: This will only remove `key`s that exist in the cache, and will do nothing if the `key` does not exist.
## update(key, value)
This will manually update the _value_ at _key_ in cache if _key_ exists. _key_ should be an `Array` of values, meant to reflect the arguments passed to the method.
```ts
// single parameter is straightforward
const memoized = moize((item: string) => item);
memoized.add(['one'], 'two');
// pulls from cache
memoized('one');
```
**NOTE**: This will only update `key`s that exist in the cache, and will do nothing if the `key` does not exist. If you want to add keys that do not already exist, use [`add`](#addkey-value).
## values()
This will return a list of the current values in `cache`.
All values provided are the number of operations per second calculated by the [Benchmark suite](https://benchmarkjs.com/), where a higher value is better. Each benchmark was performed using the default configuration of the library, with a fibonacci calculation based on a starting parameter of `35`, using single and multiple parameters with different object types. The results were averaged to determine overall speed across possible usage.
**NOTE**: `lodash`, `ramda`, and `underscore` do not support multiple-parameter memoization without use of a `resolver` function. For consistency in comparison, each use the same `resolver` that returns the result of `JSON.stringify` on the arguments.
| Name | Overall (average) | Single (average) | Multiple (average) | single primitive | single array | single object | multiple primitive | multiple array | multiple object |
`moize` is fairly small (~3.86KB when minified and gzipped), however it provides a large number of configuration options to satisfy a number of edge cases. If filesize is a concern, you may consider using [`micro-memoize`](https://github.com/planttheidea/micro-memoize). This is the memoization library that powers `moize` under-the-hood, and will handle most common use cases at 1/4 the size of `moize`.
# Browser support
- Chrome (all versions)
- Firefox (all versions)
- Edge (all versions)
- Opera 15+
- IE 9+
- Safari 6+
- iOS 8+
- Android 4+
# Development
Standard stuff, clone the repo and `npm install` dependencies. The npm scripts available:
-`benchmark` => run the benchmark suite pitting `moize` against other libraries in common use-cases
-`benchmark:alternative` => run the benchmark suite for alternative forms of caching
-`benchmark:array` => run the benchmark suite for memoized methods using single and multiple `array` parameters
-`benchmark:object` => run the benchmark suite for memoized methods using single and multiple `object` parameters
-`benchmark:primitive` => run the benchmark suite for memoized methods using single and multiple `object` parameters
-`benchmark:react` => run the benchmark suite for memoized React components
-`build` => run rollup to build the distributed files in `dist`
-`clean:dist` => run `rimraf` on the `dist` folder
-`clean:docs` => run `rimraf` on the `docs` folder
-`clean:mjs` => run `rimraf` on the `mjs` folder
-`copy:mjs` => run `clean:mjs` and the `es-to-mjs` script
-`copy:types` => copy internal types to be available for consumer
-`dev` => run webpack dev server to run example app (playground!)
-`dist` => runs `clean:dist` and `build`
-`docs` => runs `clean:docs` and builds the docs via `jsdoc`
-`flow` => runs `flow check` on the files in `src`
-`lint` => runs ESLint against all files in the `src` folder
-`lint:fix` => runs `lint`, fixing any errors if possible
-`test` => run `jest` test functions with `NODE_ENV=test`
-`test:coverage` => run `test` but with code coverage
-`test:watch` => run `test`, but with persistent watcher
-`typecheck` => run `tsc` against source code to validate TypeScript