You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

630 lines
21 KiB

1 month ago
  1. # memoize-one
  2. A memoization library that only caches the result of the most recent arguments.
  3. [![npm](https://img.shields.io/npm/v/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)
  4. ![types](https://img.shields.io/badge/types-typescript%20%7C%20flow-blueviolet)
  5. [![minzip](https://img.shields.io/bundlephobia/minzip/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)
  6. [![Downloads per month](https://img.shields.io/npm/dm/memoize-one.svg)](https://www.npmjs.com/package/memoize-one)
  7. ## Rationale
  8. 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.
  9. > For working with promises, [@Kikobeats](https://github.com/Kikobeats) has built [async-memoize-one](https://github.com/microlinkhq/async-memoize-one).
  10. ## Usage
  11. ```js
  12. // memoize-one uses the default import
  13. import memoizeOne from 'memoize-one';
  14. function add(a, b) {
  15. return a + b;
  16. }
  17. const memoizedAdd = memoizeOne(add);
  18. memoizedAdd(1, 2);
  19. // add function: is called
  20. // [new value returned: 3]
  21. memoizedAdd(1, 2);
  22. // add function: not called
  23. // [cached result is returned: 3]
  24. memoizedAdd(2, 3);
  25. // add function: is called
  26. // [new value returned: 5]
  27. memoizedAdd(2, 3);
  28. // add function: not called
  29. // [cached result is returned: 5]
  30. memoizedAdd(1, 2);
  31. // add function: is called
  32. // [new value returned: 3]
  33. // 👇
  34. // While the result of `add(1, 2)` was previously cached
  35. // `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`)
  36. // so the previous cached result of `(1, 3)` was lost
  37. ```
  38. ## Installation
  39. ```bash
  40. # yarn
  41. yarn add memoize-one
  42. # npm
  43. npm install memoize-one --save
  44. ```
  45. ## Function argument equality
  46. 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).
  47. (By default) function arguments are considered equal if:
  48. 1. there is same amount of arguments
  49. 2. each new argument has strict equality (`===`) with the previous argument
  50. 3. **[special case]** if two arguments are not `===` and they are both `NaN` then the two arguments are treated as equal
  51. What this looks like in practice:
  52. ```js
  53. import memoizeOne from 'memoize-one';
  54. // add all numbers provided to the function
  55. const add = (...args = []) =>
  56. args.reduce((current, value) => {
  57. return current + value;
  58. }, 0);
  59. const memoizedAdd = memoizeOne(add);
  60. ```
  61. > 1. there is same amount of arguments
  62. ```js
  63. memoizedAdd(1, 2);
  64. // the amount of arguments has changed, so underlying add function is called
  65. memoizedAdd(1, 2, 3);
  66. ```
  67. > 2. new arguments have strict equality (`===`) with the previous argument
  68. ```js
  69. memoizedAdd(1, 2);
  70. // each argument is `===` to the last argument, so cache is used
  71. memoizedAdd(1, 2);
  72. // second argument has changed, so add function is called again
  73. memoizedAdd(1, 3);
  74. // the first value is not `===` to the previous first value (1 !== 3)
  75. // so add function is called again
  76. memoizedAdd(3, 1);
  77. ```
  78. > 3. **[special case]** if the arguments are not `===` and they are both `NaN` then the argument is treated as equal
  79. ```js
  80. memoizedAdd(NaN);
  81. // Even though NaN !== NaN these arguments are
  82. // treated as equal as they are both `NaN`
  83. memoizedAdd(NaN);
  84. ```
  85. ## Custom equality function
  86. You can also pass in a custom function for checking the equality of two sets of arguments
  87. ```js
  88. const memoized = memoizeOne(fn, isEqual);
  89. ```
  90. An equality function should return `true` if the arguments are equal. If `true` is returned then the wrapped function will not be called.
  91. **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`.
  92. Equality functions are not called if the `this` context of the function has changed (see below).
  93. Here is an example that uses a [lodash.isEqual](https://lodash.com/docs/4.17.15#isEqual) deep equal equality check
  94. > `lodash.isequal` correctly handles deep comparing two arrays
  95. ```js
  96. import memoizeOne from 'memoize-one';
  97. import isDeepEqual from 'lodash.isequal';
  98. const identity = (x) => x;
  99. const shallowMemoized = memoizeOne(identity);
  100. const deepMemoized = memoizeOne(identity, isDeepEqual);
  101. const result1 = shallowMemoized({ foo: 'bar' });
  102. const result2 = shallowMemoized({ foo: 'bar' });
  103. result1 === result2; // false - different object reference
  104. const result3 = deepMemoized({ foo: 'bar' });
  105. const result4 = deepMemoized({ foo: 'bar' });
  106. result3 === result4; // true - arguments are deep equal
  107. ```
  108. The equality function needs to conform to the `EqualityFn` `type`:
  109. ```ts
  110. // TFunc is the function being memoized
  111. type EqualityFn<TFunc extends (...args: any[]) => any> = (
  112. newArgs: Parameters<TFunc>,
  113. lastArgs: Parameters<TFunc>,
  114. ) => boolean;
  115. // You can import this type
  116. import type { EqualityFn } from 'memoize-one';
  117. ```
  118. 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.
  119. Here are some examples of equality functions which are ordered by most type safe, to least type safe:
  120. <details>
  121. <summary>Example equality function types</summary>
  122. <p>
  123. ```ts
  124. // the function we are going to memoize
  125. function add(first: number, second: number): number {
  126. return first + second;
  127. }
  128. // Some options for our equality function
  129. // ↑ stronger types
  130. // ↓ weaker types
  131. // ✅ exact parameters of `add`
  132. {
  133. const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) {
  134. return true;
  135. };
  136. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  137. }
  138. // ✅ tuple of the correct types
  139. {
  140. const isEqual = function (first: [number, number], second: [number, number]) {
  141. return true;
  142. };
  143. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  144. }
  145. // ❌ tuple of incorrect types
  146. {
  147. const isEqual = function (first: [number, string], second: [number, number]) {
  148. return true;
  149. };
  150. expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
  151. }
  152. // ✅ array of the correct types
  153. {
  154. const isEqual = function (first: number[], second: number[]) {
  155. return true;
  156. };
  157. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  158. }
  159. // ❌ array of incorrect types
  160. {
  161. const isEqual = function (first: string[], second: number[]) {
  162. return true;
  163. };
  164. expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
  165. }
  166. // ✅ tuple of 'unknown'
  167. {
  168. const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) {
  169. return true;
  170. };
  171. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  172. }
  173. // ❌ tuple of 'unknown' of incorrect length
  174. {
  175. const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) {
  176. return true;
  177. };
  178. expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
  179. }
  180. // ✅ array of 'unknown'
  181. {
  182. const isEqual = function (first: unknown[], second: unknown[]) {
  183. return true;
  184. };
  185. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  186. }
  187. // ✅ spread of 'unknown'
  188. {
  189. const isEqual = function (...first: unknown[]) {
  190. return !!first;
  191. };
  192. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  193. }
  194. // ✅ tuple of 'any'
  195. {
  196. const isEqual = function (first: [any, any], second: [any, any]) {
  197. return true;
  198. };
  199. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  200. }
  201. // ❌ tuple of 'any' or incorrect size
  202. {
  203. const isEqual = function (first: [any, any, any], second: [any, any]) {
  204. return true;
  205. };
  206. expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>();
  207. }
  208. // ✅ array of 'any'
  209. {
  210. const isEqual = function (first: any[], second: any[]) {
  211. return true;
  212. };
  213. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  214. }
  215. // ✅ two arguments of type any
  216. {
  217. const isEqual = function (first: any, second: any) {
  218. return true;
  219. };
  220. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  221. }
  222. // ✅ a single argument of type any
  223. {
  224. const isEqual = function (first: any) {
  225. return true;
  226. };
  227. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  228. }
  229. // ✅ spread of any type
  230. {
  231. const isEqual = function (...first: any[]) {
  232. return true;
  233. };
  234. expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>();
  235. }
  236. ```
  237. </p>
  238. </details>
  239. ## `this`
  240. ### `memoize-one` correctly respects `this` control
  241. This library takes special care to maintain, and allow control over the the `this` context for **both** the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's `this` context respect [all the `this` controlling techniques](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md):
  242. - new bindings (`new`)
  243. - explicit binding (`call`, `apply`, `bind`);
  244. - implicit binding (call site: `obj.foo()`);
  245. - default binding (`window` or `undefined` in `strict mode`);
  246. - fat arrow binding (binding to lexical `this`)
  247. - ignored this (pass `null` as `this` to explicit binding)
  248. ### Changes to `this` is considered an argument change
  249. Changes to the running context (`this`) of a function can result in the function returning a different value even though its arguments have stayed the same:
  250. ```js
  251. function getA() {
  252. return this.a;
  253. }
  254. const temp1 = {
  255. a: 20,
  256. };
  257. const temp2 = {
  258. a: 30,
  259. };
  260. getA.call(temp1); // 20
  261. getA.call(temp2); // 30
  262. ```
  263. Therefore, in order to prevent against unexpected results, `memoize-one` takes into account the current execution context (`this`) of the memoized function. If `this` is different to the previous invocation then it is considered a change in argument. [further discussion](https://github.com/alexreardon/memoize-one/issues/3).
  264. Generally this will be of no impact if you are not explicity controlling the `this` context of functions you want to memoize with [explicit binding](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#explicit-binding) or [implicit binding](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#implicit-binding). `memoize-One` will detect when you are manipulating `this` and will then consider the `this` context as an argument. If `this` changes, it will re-execute the original function even if the arguments have not changed.
  265. ## Clearing the memoization cache
  266. A `.clear()` property is added to memoized functions to allow you to clear it's memoization cache.
  267. This is helpful if you want to:
  268. - Release memory
  269. - Allow the underlying function to be called again without having to change arguments
  270. ```ts
  271. import memoizeOne from 'memoize-one';
  272. function add(a: number, b: number): number {
  273. return a + b;
  274. }
  275. const memoizedAdd = memoizeOne(add);
  276. // first call - not memoized
  277. const first = memoizedAdd(1, 2);
  278. // second call - cache hit (underlying function not called)
  279. const second = memoizedAdd(1, 2);
  280. // 👋 clearing memoization cache
  281. memoizedAdd.clear();
  282. // third call - not memoized (cache was cleared)
  283. const third = memoizedAdd(1, 2);
  284. ```
  285. ## When your result function `throw`s
  286. > There is no caching when your result function throws
  287. If your result function `throw`s then the memoized function will also throw. The throw will not break the memoized functions existing argument cache. It means the memoized function will pretend like it was never called with arguments that made it `throw`.
  288. ```js
  289. const canThrow = (name: string) => {
  290. console.log('called');
  291. if (name === 'throw') {
  292. throw new Error(name);
  293. }
  294. return { name };
  295. };
  296. const memoized = memoizeOne(canThrow);
  297. const value1 = memoized('Alex');
  298. // console.log => 'called'
  299. const value2 = memoized('Alex');
  300. // result function not called
  301. console.log(value1 === value2);
  302. // console.log => true
  303. try {
  304. memoized('throw');
  305. // console.log => 'called'
  306. } catch (e) {
  307. firstError = e;
  308. }
  309. try {
  310. memoized('throw');
  311. // console.log => 'called'
  312. // the result function was called again even though it was called twice
  313. // with the 'throw' string
  314. } catch (e) {
  315. secondError = e;
  316. }
  317. console.log(firstError !== secondError);
  318. const value3 = memoized('Alex');
  319. // result function not called as the original memoization cache has not been busted
  320. console.log(value1 === value3);
  321. // console.log => true
  322. ```
  323. ## Function properties
  324. Functions memoized with `memoize-one` do not preserve any properties on the function object.
  325. > This behaviour correctly reflected in the TypeScript types
  326. ```ts
  327. import memoizeOne from 'memoize-one';
  328. function add(a, b) {
  329. return a + b;
  330. }
  331. add.hello = 'hi';
  332. console.log(typeof add.hello); // string
  333. const memoized = memoizeOne(add);
  334. // hello property on the `add` was not preserved
  335. console.log(typeof memoized.hello); // undefined
  336. ```
  337. 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.
  338. For _now_, the `.length` property of a function is not preserved on the memoized function
  339. ```ts
  340. import memoizeOne from 'memoize-one';
  341. function add(a, b) {
  342. return a + b;
  343. }
  344. console.log(add.length); // 2
  345. const memoized = memoizeOne(add);
  346. console.log(memoized.length); // 0
  347. ```
  348. 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
  349. [→ discussion](https://github.com/alexreardon/memoize-one/pull/124).
  350. ## Memoized function `type`
  351. The resulting function you get back from `memoize-one` has *almost* the same `type` as the function that you are memoizing
  352. ```ts
  353. declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = {
  354. clear: () => void;
  355. (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>;
  356. };
  357. ```
  358. - the same call signature as the function being memoized
  359. - a `.clear()` function property added
  360. - other function object properties on `TFunc` as not carried over
  361. You are welcome to use the `MemoizedFn` generic directly from `memoize-one` if you like:
  362. ```ts
  363. import memoize, { MemoizedFn } from 'memoize-one';
  364. import isDeepEqual from 'lodash.isequal';
  365. import { expectTypeOf } from 'expect-type';
  366. // Takes any function: TFunc, and returns a Memoized<TFunc>
  367. function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc): MemoizedFn<TFunc> {
  368. return memoize(fn, isDeepEqual);
  369. }
  370. function add(first: number, second: number): number {
  371. return first + second;
  372. }
  373. const memoized = withDeepEqual(add);
  374. expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();
  375. ```
  376. In this specific example, this type would have been correctly inferred too
  377. ```ts
  378. import memoize, { MemoizedFn } from 'memoize-one';
  379. import isDeepEqual from 'lodash.isequal';
  380. import { expectTypeOf } from 'expect-type';
  381. // return type of MemoizedFn<TFunc> is inferred
  382. function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc) {
  383. return memoize(fn, isDeepEqual);
  384. }
  385. function add(first: number, second: number): number {
  386. return first + second;
  387. }
  388. const memoized = withDeepEqual(add);
  389. // type test still passes
  390. expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();
  391. ```
  392. ## Performance 🚀
  393. ### Tiny
  394. `memoize-one` is super lightweight at [![min](https://img.shields.io/bundlephobia/min/memoize-one.svg?label=)](https://www.npmjs.com/package/memoize-one) minified and [![minzip](https://img.shields.io/bundlephobia/minzip/memoize-one.svg?label=)](https://www.npmjs.com/package/memoize-one) gzipped. (`1KB` = `1,024 Bytes`)
  395. ### Extremely fast
  396. `memoize-one` performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.
  397. 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.
  398. <details>
  399. <summary>Expand for results</summary>
  400. <p>
  401. node version `16.11.1`
  402. You can run this test in the repo by:
  403. 1. Add `"type": "module"` to the `package.json` (why is things so hard)
  404. 2. Run `yarn perf:library-comparison`
  405. **no arguments**
  406. | Position | Library | Operations per second |
  407. | -------- | -------------------------------------------- | --------------------- |
  408. | 1 | memoize-one | 80,112,981 |
  409. | 2 | moize | 72,885,631 |
  410. | 3 | memoizee | 35,550,009 |
  411. | 4 | mem (JSON.stringify strategy) | 4,610,532 |
  412. | 5 | lodash.memoize (JSON.stringify key resolver) | 3,708,945 |
  413. | 6 | no memoization | 505 |
  414. | 7 | fast-memoize | 504 |
  415. **single primitive argument**
  416. | Position | Library | Operations per second |
  417. | -------- | -------------------------------------------- | --------------------- |
  418. | 1 | fast-memoize | 45,482,711 |
  419. | 2 | moize | 34,810,659 |
  420. | 3 | memoize-one | 29,030,828 |
  421. | 4 | memoizee | 23,467,065 |
  422. | 5 | mem (JSON.stringify strategy) | 3,985,223 |
  423. | 6 | lodash.memoize (JSON.stringify key resolver) | 3,369,297 |
  424. | 7 | no memoization | 507 |
  425. **single complex argument**
  426. | Position | Library | Operations per second |
  427. | -------- | -------------------------------------------- | --------------------- |
  428. | 1 | moize | 27,660,856 |
  429. | 2 | memoize-one | 22,407,916 |
  430. | 3 | memoizee | 19,546,835 |
  431. | 4 | mem (JSON.stringify strategy) | 2,068,038 |
  432. | 5 | lodash.memoize (JSON.stringify key resolver) | 1,911,335 |
  433. | 6 | fast-memoize | 1,633,855 |
  434. | 7 | no memoization | 504 |
  435. **multiple primitive arguments**
  436. | Position | Library | Operations per second |
  437. | -------- | -------------------------------------------- | --------------------- |
  438. | 1 | moize | 22,366,497 |
  439. | 2 | memoize-one | 17,241,995 |
  440. | 3 | memoizee | 9,789,442 |
  441. | 4 | mem (JSON.stringify strategy) | 3,065,328 |
  442. | 5 | lodash.memoize (JSON.stringify key resolver) | 2,663,599 |
  443. | 6 | fast-memoize | 1,219,548 |
  444. | 7 | no memoization | 504 |
  445. **multiple complex arguments**
  446. | Position | Library | Operations per second |
  447. | -------- | -------------------------------------------- | --------------------- |
  448. | 1 | moize | 21,788,081 |
  449. | 2 | memoize-one | 17,321,248 |
  450. | 3 | memoizee | 9,595,420 |
  451. | 4 | lodash.memoize (JSON.stringify key resolver) | 873,283 |
  452. | 5 | mem (JSON.stringify strategy) | 850,779 |
  453. | 6 | fast-memoize | 687,863 |
  454. | 7 | no memoization | 504 |
  455. **multiple complex arguments (spreading arguments)**
  456. | Position | Library | Operations per second |
  457. | -------- | -------------------------------------------- | --------------------- |
  458. | 1 | moize | 21,701,537 |
  459. | 2 | memoizee | 19,463,942 |
  460. | 3 | memoize-one | 17,027,544 |
  461. | 4 | lodash.memoize (JSON.stringify key resolver) | 887,816 |
  462. | 5 | mem (JSON.stringify strategy) | 849,244 |
  463. | 6 | fast-memoize | 691,512 |
  464. | 7 | no memoization | 504 |
  465. </p>
  466. </details>
  467. ## Code health 👍
  468. - Tested with all built in [JavaScript types](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch1.md)
  469. - Written in `Typescript`
  470. - Correct typing for `Typescript` and `flow` type systems
  471. - No dependencies