memoize-one
Advanced tools
Comparing version 5.2.1 to 6.0.0-beta.1
@@ -30,6 +30,3 @@ 'use strict'; | ||
if (isEqual === void 0) { isEqual = areInputsEqual; } | ||
var lastThis; | ||
var lastArgs = []; | ||
var lastResult; | ||
var calledOnce = false; | ||
var cache = null; | ||
function memoized() { | ||
@@ -40,11 +37,16 @@ var newArgs = []; | ||
} | ||
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) { | ||
return lastResult; | ||
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) { | ||
return cache.lastResult; | ||
} | ||
lastResult = resultFn.apply(this, newArgs); | ||
calledOnce = true; | ||
lastThis = this; | ||
lastArgs = newArgs; | ||
var lastResult = resultFn.apply(this, newArgs); | ||
cache = { | ||
lastResult: lastResult, | ||
lastArgs: newArgs, | ||
lastThis: this, | ||
}; | ||
return lastResult; | ||
} | ||
memoized.clear = function clear() { | ||
cache = null; | ||
}; | ||
return memoized; | ||
@@ -51,0 +53,0 @@ } |
@@ -1,3 +0,7 @@ | ||
export declare type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean; | ||
declare function memoizeOne<ResultFn extends (this: any, ...newArgs: any[]) => ReturnType<ResultFn>>(resultFn: ResultFn, isEqual?: EqualityFn): ResultFn; | ||
export declare type EqualityFn<TFunc extends (...args: any[]) => any> = (newArgs: Parameters<TFunc>, lastArgs: Parameters<TFunc>) => boolean; | ||
declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = { | ||
clear: () => void; | ||
(this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>; | ||
}; | ||
declare function memoizeOne<TFunc extends (this: any, ...newArgs: any[]) => any>(resultFn: TFunc, isEqual?: EqualityFn<TFunc>): MemoizedFn<TFunc>; | ||
export default memoizeOne; |
@@ -28,6 +28,3 @@ var safeIsNaN = Number.isNaN || | ||
if (isEqual === void 0) { isEqual = areInputsEqual; } | ||
var lastThis; | ||
var lastArgs = []; | ||
var lastResult; | ||
var calledOnce = false; | ||
var cache = null; | ||
function memoized() { | ||
@@ -38,14 +35,19 @@ var newArgs = []; | ||
} | ||
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) { | ||
return lastResult; | ||
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) { | ||
return cache.lastResult; | ||
} | ||
lastResult = resultFn.apply(this, newArgs); | ||
calledOnce = true; | ||
lastThis = this; | ||
lastArgs = newArgs; | ||
var lastResult = resultFn.apply(this, newArgs); | ||
cache = { | ||
lastResult: lastResult, | ||
lastArgs: newArgs, | ||
lastThis: this, | ||
}; | ||
return lastResult; | ||
} | ||
memoized.clear = function clear() { | ||
cache = null; | ||
}; | ||
return memoized; | ||
} | ||
export default memoizeOne; | ||
export { memoizeOne as default }; |
@@ -5,3 +5,3 @@ (function (global, factory) { | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.memoizeOne = factory()); | ||
}(this, (function () { 'use strict'; | ||
})(this, (function () { 'use strict'; | ||
@@ -35,6 +35,3 @@ var safeIsNaN = Number.isNaN || | ||
if (isEqual === void 0) { isEqual = areInputsEqual; } | ||
var lastThis; | ||
var lastArgs = []; | ||
var lastResult; | ||
var calledOnce = false; | ||
var cache = null; | ||
function memoized() { | ||
@@ -45,11 +42,16 @@ var newArgs = []; | ||
} | ||
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) { | ||
return lastResult; | ||
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) { | ||
return cache.lastResult; | ||
} | ||
lastResult = resultFn.apply(this, newArgs); | ||
calledOnce = true; | ||
lastThis = this; | ||
lastArgs = newArgs; | ||
var lastResult = resultFn.apply(this, newArgs); | ||
cache = { | ||
lastResult: lastResult, | ||
lastArgs: newArgs, | ||
lastThis: this, | ||
}; | ||
return lastResult; | ||
} | ||
memoized.clear = function clear() { | ||
cache = null; | ||
}; | ||
return memoized; | ||
@@ -60,2 +62,2 @@ } | ||
}))); | ||
})); |
@@ -1,1 +0,1 @@ | ||
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).memoizeOne=n()}(this,(function(){"use strict";var e=Number.isNaN||function(e){return"number"==typeof e&&e!=e};function n(n,t){if(n.length!==t.length)return!1;for(var r=0;r<n.length;r++)if(i=n[r],o=t[r],!(i===o||e(i)&&e(o)))return!1;var i,o;return!0}return function(e,t){var r;void 0===t&&(t=n);var i,o=[],f=!1;return function(){for(var n=[],u=0;u<arguments.length;u++)n[u]=arguments[u];return f&&r===this&&t(n,o)||(i=e.apply(this,n),f=!0,r=this,o=n),i}}})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).memoizeOne=t()}(this,(function(){"use strict";var e=Number.isNaN||function(e){return"number"==typeof e&&e!=e};function t(t,n){if(t.length!==n.length)return!1;for(var r=0;r<t.length;r++)if(i=t[r],u=n[r],!(i===u||e(i)&&e(u)))return!1;var i,u;return!0}return function(e,n){void 0===n&&(n=t);var r=null;function i(){for(var t=[],i=0;i<arguments.length;i++)t[i]=arguments[i];if(r&&r.lastThis===this&&n(t,r.lastArgs))return r.lastResult;var u=e.apply(this,t);return r={lastResult:u,lastArgs:t,lastThis:this},u}return i.clear=function(){r=null},i}})); |
{ | ||
"name": "memoize-one", | ||
"version": "5.2.1", | ||
"version": "6.0.0-beta.1", | ||
"description": "A memoization library which only remembers the latest invocation", | ||
@@ -22,15 +22,15 @@ "main": "dist/memoize-one.cjs.js", | ||
"path": "dist/memoize-one.min.js", | ||
"limit": "214B" | ||
"limit": "234B" | ||
}, | ||
{ | ||
"path": "dist/memoize-one.js", | ||
"limit": "216B" | ||
"limit": "234B" | ||
}, | ||
{ | ||
"path": "dist/memoize-one.cjs.js", | ||
"limit": "213B" | ||
"limit": "230B" | ||
}, | ||
{ | ||
"path": "dist/memoize-one.esm.js", | ||
"limit": "218B" | ||
"limit": "246B" | ||
} | ||
@@ -46,26 +46,38 @@ ], | ||
"devDependencies": { | ||
"@size-limit/preset-small-lib": "^4.10.2", | ||
"@types/jest": "^26.0.22", | ||
"@size-limit/preset-small-lib": "^5.0.4", | ||
"@types/benchmark": "^2.1.1", | ||
"@types/jest": "^27.0.2", | ||
"@types/lodash.isequal": "^4.5.5", | ||
"@typescript-eslint/eslint-plugin": "^4.22.0", | ||
"@typescript-eslint/parser": "^4.22.0", | ||
"@types/lodash.memoize": "^4.1.6", | ||
"@types/node": "^16.10.1", | ||
"@typescript-eslint/eslint-plugin": "^4.31.2", | ||
"@typescript-eslint/parser": "^4.31.2", | ||
"benchmark": "^2.1.4", | ||
"cli-table": "^0.3.6", | ||
"cross-env": "^7.0.3", | ||
"eslint": "7.24.0", | ||
"eslint-config-prettier": "^8.1.0", | ||
"eslint-plugin-jest": "^24.3.5", | ||
"eslint-plugin-prettier": "^3.3.1", | ||
"jest": "^26.6.3", | ||
"eslint": "7.32.0", | ||
"eslint-config-prettier": "^8.3.0", | ||
"eslint-plugin-jest": "^24.4.2", | ||
"eslint-plugin-prettier": "^4.0.0", | ||
"expect-type": "^0.12.0", | ||
"fast-memoize": "^2.5.2", | ||
"jest": "^27.2.2", | ||
"lodash.isequal": "^4.5.0", | ||
"prettier": "2.2.1", | ||
"lodash.memoize": "^4.1.2", | ||
"mem": "^9.0.1", | ||
"memoizee": "^0.4.15", | ||
"moize": "^6.1.0", | ||
"nanocolors": "^0.2.9", | ||
"ora": "^6.0.1", | ||
"prettier": "2.4.1", | ||
"rimraf": "3.0.2", | ||
"rollup": "^2.45.1", | ||
"rollup": "^2.57.0", | ||
"rollup-plugin-replace": "^2.2.0", | ||
"rollup-plugin-terser": "^7.0.2", | ||
"rollup-plugin-typescript": "^1.0.1", | ||
"size-limit": "^4.10.2", | ||
"ts-jest": "^26.5.4", | ||
"ts-node": "^9.1.1", | ||
"tslib": "^2.2.0", | ||
"typescript": "^4.2.4" | ||
"size-limit": "^5.0.4", | ||
"ts-jest": "^27.0.5", | ||
"ts-node": "^10.2.1", | ||
"tslib": "^2.3.1", | ||
"typescript": "^4.4.3" | ||
}, | ||
@@ -76,18 +88,18 @@ "config": { | ||
"scripts": { | ||
"validate": "yarn lint && yarn typecheck", | ||
"validate": "yarn prettier:check && yarn eslint:check && yarn typescript:check", | ||
"test": "yarn jest", | ||
"test:size": "yarn build && size-limit", | ||
"typecheck": "yarn tsc --noEmit", | ||
"test:size": "yarn build && yarn size-limit", | ||
"typescript:check": "yarn tsc --noEmit", | ||
"prettier:check": "yarn prettier --debug-check $npm_package_config_prettier_target", | ||
"prettier:write": "yarn prettier --write $npm_package_config_prettier_target", | ||
"lint:eslint": "eslint $npm_package_config_prettier_target", | ||
"lint": "yarn lint:eslint && yarn prettier:check", | ||
"eslint:check": "eslint $npm_package_config_prettier_target", | ||
"build": "yarn build:clean && yarn build:dist && yarn build:typescript && yarn build:flow", | ||
"build:clean": "rimraf dist", | ||
"build:dist": "rollup -c", | ||
"build:typescript": "tsc ./src/memoize-one.ts --emitDeclarationOnly --declaration --outDir ./dist", | ||
"build:clean": "yarn rimraf dist", | ||
"build:dist": "yarn rollup -c", | ||
"build:typescript": "yarn tsc ./src/memoize-one.ts --emitDeclarationOnly --declaration --outDir ./dist", | ||
"build:flow": "cp src/memoize-one.js.flow dist/memoize-one.cjs.js.flow", | ||
"perf": "ts-node ./benchmarks/shallow-equal.ts", | ||
"perf": "yarn ts-node ./benchmarks/shallow-equal.ts", | ||
"perf:library-comparison": "yarn build && node ./benchmarks/library-comparison.js", | ||
"prepublishOnly": "yarn build" | ||
} | ||
} |
384
README.md
@@ -16,3 +16,3 @@ # memoize-one | ||
Unlike other memoization libraries, `memoize-one` only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as `maxAge`, `maxSize`, `exclusions` and so on, which can be prone to memory leaks. `memoize-one` simply remembers the last arguments, and if the function is next called with the same arguments then it returns the previous result. | ||
Unlike other memoization libraries, `memoize-one` only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as `maxAge`, `maxSize`, `exclusions` and so on, which can be prone to memory leaks. A function memoized with `memoize-one` simply remembers the last arguments, and if the memoized function is next called with the same arguments then it returns the previous result. | ||
@@ -25,20 +25,30 @@ ## Usage | ||
const add = (a, b) => a + b; | ||
function add(a, b) { | ||
return a + b; | ||
} | ||
const memoizedAdd = memoizeOne(add); | ||
memoizedAdd(1, 2); // 3 | ||
memoizedAdd(1, 2); | ||
// add function: is called | ||
// [new value returned: 3] | ||
memoizedAdd(1, 2); // 3 | ||
// Add function is not executed: previous result is returned | ||
memoizedAdd(1, 2); | ||
// add function: not called | ||
// [cached result is returned: 3] | ||
memoizedAdd(2, 3); // 5 | ||
// Add function is called to get new value | ||
memoizedAdd(2, 3); | ||
// add function: is called | ||
// [new value returned: 5] | ||
memoizedAdd(2, 3); // 5 | ||
// Add function is not executed: previous result is returned | ||
memoizedAdd(2, 3); | ||
// add function: not called | ||
// [cached result is returned: 5] | ||
memoizedAdd(1, 2); // 3 | ||
// Add function is called to get new value. | ||
// While this was previously cached, | ||
// it is not the latest so the cached result is lost | ||
memoizedAdd(1, 2); | ||
// add function: is called | ||
// [new value returned: 3] | ||
// 👇 | ||
// While the result of `add(1, 2)` was previously cached | ||
// `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`) | ||
// so the previous cached result of `(1, 3)` was lost | ||
``` | ||
@@ -58,3 +68,3 @@ | ||
By default, we apply our own _fast_ and _naive_ equality function to determine whether the arguments provided to your function are equal. You can see the full code here: [are-inputs-equal.ts](https://github.com/alexreardon/memoize-one/blob/master/src/are-inputs-equal.ts). | ||
By default, we apply our own _fast_ and _relatively naive_ equality function to determine whether the arguments provided to your function are equal. You can see the full code here: [are-inputs-equal.ts](https://github.com/alexreardon/memoize-one/blob/master/src/are-inputs-equal.ts). | ||
@@ -105,3 +115,4 @@ (By default) function arguments are considered equal if: | ||
memoizedAdd(NaN); | ||
// Even though NaN !== NaN these arguments are treated as equal | ||
// Even though NaN !== NaN these arguments are | ||
// treated as equal as they are both `NaN` | ||
memoizedAdd(NaN); | ||
@@ -118,19 +129,5 @@ ``` | ||
The equality function needs to conform to this `type`: | ||
```ts | ||
type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean; | ||
// You can import this type from memoize-one if you like | ||
// typescript | ||
import { EqualityFn } from 'memoize-one'; | ||
// flow | ||
import type { EqualityFn } from 'memoize-one'; | ||
``` | ||
An equality function should return `true` if the arguments are equal. If `true` is returned then the wrapped function will not be called. | ||
A custom equality function needs to compare `Arrays`. The `newArgs` array will be a new reference every time so a simple `newArgs === lastArgs` will always return `false`. | ||
**Tip**: A custom equality function needs to compare `Arrays`. The `newArgs` array will be a new reference every time so a simple `newArgs === lastArgs` will always return `false`. | ||
@@ -141,7 +138,7 @@ Equality functions are not called if the `this` context of the function has changed (see below). | ||
> `dequal` correctly handles deep comparing two arrays | ||
> `lodash.isequal` correctly handles deep comparing two arrays | ||
```js | ||
import memoizeOne from 'memoize-one'; | ||
import { dequal as isDeepEqual } from 'dequal'; | ||
import isDeepEqual from 'lodash.isequal'; | ||
@@ -164,2 +161,157 @@ const identity = (x) => x; | ||
The equality function needs to conform to the `EqualityFn` `type`: | ||
```ts | ||
// TFunc is the function being memoized | ||
type EqualityFn<TFunc extends (...args: any[]) => any> = ( | ||
newArgs: Parameters<TFunc>, | ||
lastArgs: Parameters<TFunc>, | ||
) => boolean; | ||
// You can import this type | ||
import type { EqualityFn } from 'memoize-one'; | ||
``` | ||
The `EqualityFn` type allows you to create equality functions that are extremely typesafe. You are welcome to provide your own less type safe equality functions. | ||
Here are some examples of equality functions which are ordered by most type safe, to least type safe: | ||
<details> | ||
<summary>Example equality function types</summary> | ||
<p> | ||
```ts | ||
// the function we are going to memoize | ||
function add(first: number, second: number): number { | ||
return first + second; | ||
} | ||
// Some options for our equality function | ||
// ↑ stronger types | ||
// ↓ weaker types | ||
// ✅ exact parameters of `add` | ||
{ | ||
const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ tuple of the correct types | ||
{ | ||
const isEqual = function (first: [number, number], second: [number, number]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ❌ tuple of incorrect types | ||
{ | ||
const isEqual = function (first: [number, string], second: [number, number]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ array of the correct types | ||
{ | ||
const isEqual = function (first: number[], second: number[]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ❌ array of incorrect types | ||
{ | ||
const isEqual = function (first: string[], second: number[]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ tuple of 'unknown' | ||
{ | ||
const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ❌ tuple of 'unknown' of incorrect length | ||
{ | ||
const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ array of 'unknown' | ||
{ | ||
const isEqual = function (first: unknown[], second: unknown[]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ spread of 'unknown' | ||
{ | ||
const isEqual = function (...first: unknown[]) { | ||
return !!first; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ tuple of 'any' | ||
{ | ||
const isEqual = function (first: [any, any], second: [any, any]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ❌ tuple of 'any' or incorrect size | ||
{ | ||
const isEqual = function (first: [any, any, any], second: [any, any]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ array of 'any' | ||
{ | ||
const isEqual = function (first: any[], second: any[]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ two arguments of type any | ||
{ | ||
const isEqual = function (first: any, second: any) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ a single argument of type any | ||
{ | ||
const isEqual = function (first: any) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
// ✅ spread of any type | ||
{ | ||
const isEqual = function (...first: any[]) { | ||
return true; | ||
}; | ||
expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); | ||
} | ||
``` | ||
</p> | ||
</details> | ||
## `this` | ||
@@ -202,2 +354,33 @@ | ||
## Clearing the memoization cache | ||
A `.clear()` property is added to memoized functions to allow you to clear it's memoization cache. | ||
This is helpful if you want to: | ||
- Clear memory | ||
- Cause the underlying function to be called again without having to change arguments | ||
```ts | ||
import memoizeOne from 'memoize-one'; | ||
function add(a: number, b: number): number { | ||
return a + b; | ||
} | ||
const memoizedAdd = memoizeOne(add); | ||
// first call - not memoized | ||
const first = memoizedAdd(1, 2); | ||
// second call - cache hit (underlying function not called) | ||
const second = memoizedAdd(1, 2); | ||
// 👋 clearing memoization cache | ||
memoizedAdd.clear(); | ||
// third call - not memoized (cache was cleared) | ||
const third = memoizedAdd(1, 2); | ||
``` | ||
## When your result function `throw`s | ||
@@ -252,2 +435,46 @@ | ||
## Function properties | ||
Functions memoized with `memoize-one` do not preserve any properties on the function object. | ||
> This behaviour correctly reflected in the TypeScript types | ||
```ts | ||
import memoizeOne from 'memoize-one'; | ||
function add(a, b) { | ||
return a + b; | ||
} | ||
add.hello = 'hi'; | ||
console.log(typeof add.hello); // string | ||
const memoized = memoizeOne(add); | ||
// hello property on the `add` was not preserved | ||
console.log(typeof memoized.hello); // undefined | ||
``` | ||
If you feel strongly that `memoize-one` _should_ preserve function properties, please raise an issue. This decision was made in order to keep `memoize-one` as light as possible. | ||
For _now_, the `.length` property of a function is not preserved on the memoized function | ||
```ts | ||
import memoizeOne from 'memoize-one'; | ||
function add(a, b) { | ||
return a + b; | ||
} | ||
console.log(add.length); // 2 | ||
const memoized = memoizeOne(add); | ||
console.log(memoized.length); // 0 | ||
``` | ||
There is no (great) way to correctly set the `.length` property of the memoized function while also supporting ie11. Once we [remove ie11 support](https://github.com/alexreardon/memoize-one/issues/125) then we will set the `.length` property of the memoized function to match the original function | ||
[→ discussion](https://github.com/alexreardon/memoize-one/pull/124). | ||
## Performance 🚀 | ||
@@ -263,16 +490,95 @@ | ||
**Results** | ||
The comparisons are not exhaustive and are primarily to show that `memoize-one` accomplishes remembering the latest invocation really fast. There is variability between runs. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on. | ||
- [simple arguments](https://www.measurethat.net/Benchmarks/ShowResult/4452) | ||
- [complex arguments](https://www.measurethat.net/Benchmarks/ShowResult/4488) | ||
<details> | ||
<summary>Expand for results</summary> | ||
<p> | ||
The comparisons are not exhaustive and are primarily to show that `memoize-one` accomplishes remembering the latest invocation really fast. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on. | ||
node version `14.15.0` | ||
You can run this test in the repo by: | ||
1. Add `"type": "module"` to the `package.json` (why is things so hard) | ||
2. Run `yarn perf:library-comparison` | ||
**no arguments** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | memoize-one | 80,657,220 | | ||
| 2 | moize | 64,951,103 | | ||
| 3 | memoizee | 32,066,963 | | ||
| 4 | lodash.memoize | 30,387,390 | | ||
| 5 | mem (JSON.stringify strategy) | 3,894,072 | | ||
| 6 | no memoization | 506 | | ||
| 7 | fast-memoize | 505 | | ||
**single primitive argument** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | fast-memoize | 43,922,254 | | ||
| 2 | lodash.memoize | 26,652,387 | | ||
| 3 | moize | 25,654,686 | | ||
| 4 | memoize-one | 25,059,187 | | ||
| 5 | memoizee | 19,096,104 | | ||
| 6 | mem (JSON.stringify strategy) | 3,448,488 | | ||
| 7 | no memoization | 503 | | ||
**single complex argument** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | moize | 31,199,164 | | ||
| 2 | lodash.memoize | 28,712,860 | | ||
| 3 | memoize-one | 23,896,851 | | ||
| 4 | memoizee | 19,010,167 | | ||
| 5 | mem (JSON.stringify strategy) | 2,045,973 | | ||
| 6 | fast-memoize | 1,519,294 | | ||
| 7 | no memoization | 504 | | ||
**multiple primitive arguments** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | moize | 21,039,928 | | ||
| 2 | lodash.memoize | 20,248,759 | | ||
| 3 | memoize-one | 16,600,643 | | ||
| 4 | memoizee | 9,071,600 | | ||
| 5 | mem (JSON.stringify strategy) | 2,990,592 | | ||
| 6 | fast-memoize | 1,156,061 | | ||
| 7 | no memoization | 506 | | ||
**multiple complex arguments** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | lodash.memoize | 22,803,155 | | ||
| 2 | moize | 19,773,333 | | ||
| 3 | memoize-one | 16,341,253 | | ||
| 4 | memoizee | 9,030,317 | | ||
| 5 | mem (JSON.stringify strategy) | 806,040 | | ||
| 6 | fast-memoize | 633,057 | | ||
| 7 | no memoization | 504 | | ||
**multiple complex arguments (spreading arguments)** | ||
| Position | Library | Operations per second | | ||
| -------- | ----------------------------- | --------------------- | | ||
| 1 | lodash.memoize | 24,089,032 | | ||
| 2 | moize | 21,574,025 | | ||
| 3 | memoizee | 19,810,230 | | ||
| 4 | memoize-one | 16,201,443 | | ||
| 5 | mem (JSON.stringify strategy) | 861,279 | | ||
| 6 | fast-memoize | 656,715 | | ||
| 7 | no memoization | 504 | | ||
</p> | ||
</details> | ||
## Code health 👍 | ||
- Tested with all built in [JavaScript types](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch1.md). | ||
- 100% code coverage | ||
- [Continuous integration](https://travis-ci.org/alexreardon/memoize-one) to run tests and type checks. | ||
- Tested with all built in [JavaScript types](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch1.md) | ||
- Written in `Typescript` | ||
- Correct typing for `Typescript` and `flow` type systems | ||
- No dependencies |
@@ -7,2 +7,4 @@ // Number.isNaN as it is not supported in IE11 so conditionally using ponyfill | ||
function ponyfill(value: unknown): boolean { | ||
// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#polyfill | ||
// NaN is the only value in JavaScript which is not equal to itself. | ||
return typeof value === 'number' && value !== value; | ||
@@ -9,0 +11,0 @@ }; |
import areInputsEqual from './are-inputs-equal'; | ||
// Using ReadonlyArray<T> rather than readonly T as it works with TS v3 | ||
export type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean; | ||
export type EqualityFn<TFunc extends (...args: any[]) => any> = ( | ||
newArgs: Parameters<TFunc>, | ||
lastArgs: Parameters<TFunc>, | ||
) => boolean; | ||
function memoizeOne< | ||
// Need to use 'any' rather than 'unknown' here as it has | ||
// The correct Generic narrowing behaviour. | ||
ResultFn extends (this: any, ...newArgs: any[]) => ReturnType<ResultFn> | ||
>(resultFn: ResultFn, isEqual: EqualityFn = areInputsEqual): ResultFn { | ||
let lastThis: unknown; | ||
let lastArgs: unknown[] = []; | ||
let lastResult: ReturnType<ResultFn>; | ||
let calledOnce: boolean = false; | ||
type Cache<TFunc extends (this: any, ...args: any[]) => any> = { | ||
lastThis: ThisParameterType<TFunc>; | ||
lastArgs: Parameters<TFunc>; | ||
lastResult: ReturnType<TFunc>; | ||
}; | ||
type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = { | ||
clear: () => void; | ||
(this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>; | ||
}; | ||
function memoizeOne<TFunc extends (this: any, ...newArgs: any[]) => any>( | ||
resultFn: TFunc, | ||
isEqual: EqualityFn<TFunc> = areInputsEqual, | ||
): MemoizedFn<TFunc> { | ||
let cache: Cache<TFunc> | null = null; | ||
// breaking cache when context (this) or arguments change | ||
function memoized(this: unknown, ...newArgs: unknown[]): ReturnType<ResultFn> { | ||
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) { | ||
return lastResult; | ||
function memoized( | ||
this: ThisParameterType<TFunc>, | ||
...newArgs: Parameters<TFunc> | ||
): ReturnType<TFunc> { | ||
if (cache && cache.lastThis === this && isEqual(newArgs, cache.lastArgs)) { | ||
return cache.lastResult; | ||
} | ||
@@ -24,18 +36,21 @@ | ||
// Doing the lastResult assignment first so that if it throws | ||
// nothing will be overwritten | ||
lastResult = resultFn.apply(this, newArgs); | ||
calledOnce = true; | ||
lastThis = this; | ||
lastArgs = newArgs; | ||
// the cache will not be overwritten | ||
const lastResult = resultFn.apply(this, newArgs); | ||
cache = { | ||
lastResult, | ||
lastArgs: newArgs, | ||
lastThis: this, | ||
}; | ||
return lastResult; | ||
} | ||
return memoized as ResultFn; | ||
// Adding the ability to clear the cache of a memoized function | ||
memoized.clear = function clear() { | ||
cache = null; | ||
}; | ||
return memoized; | ||
} | ||
// default export | ||
export default memoizeOne; | ||
// disabled for now as mixing named and | ||
// default exports is problematic with CommonJS | ||
// export { memoizeOne }; |
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
32957
246
575
36
1