Debian Codegraph @

memoizee/README.md

raw
1 [![Build status][build-image]][build-url]
2 [![Tests coverage][cov-image]][cov-url]
3 [![npm version][npm-image]][npm-url]
4
5 # Memoizee
6
7 ## Complete memoize/cache solution for JavaScript
8
9 _Originally derived from [es5-ext](https://github.com/medikoo/es5-ext) package._
10
11 Memoization is best technique to save on memory or CPU cycles when we deal with repeated operations. For detailed insight see: http://en.wikipedia.org/wiki/Memoization
12
13 ### Features
14
15 - Works with any type of function arguments – **no serialization is needed**
16 - Works with [**any length of function arguments**](#arguments-length). Length can be set as fixed or dynamic.
17 - One of the [**fastest**](#benchmarks) available solutions.
18 - Support for [**promises**](#promise-returning-functions) and [**asynchronous functions**](#nodejs-callback-style-functions)
19 - [**Primitive mode**](#primitive-mode) which assures fast performance when arguments are convertible to strings.
20 - [**WeakMap based mode**](#weakmap-based-configurations) for garbage collection friendly configuration
21 - Can be configured [**for methods**](#memoizing-methods) (when `this` counts in)
22 - Cache [**can be cleared manually**](#manual-clean-up) or [**after specified timeout**](#expire-cache-after-given-period-of-time)
23 - Cache size can be **[limited on LRU basis](#limiting-cache-size)**
24 - Optionally [**accepts resolvers**](#argument-resolvers) that normalize function arguments before passing them to underlying function.
25 - Optional [**reference counter mode**](#reference-counter), that allows more sophisticated cache management
26 - [**Profile tool**](#profiling--statistics) that provides valuable usage statistics
27 - Covered by [**over 500 unit tests**](#tests)
28
29 ### Installation
30
31 In your project path — **note the two `e`'s in `memoizee`:**
32
33 ```shell
34 $ npm install memoizee
35 # or with yarn
36 $ yarn add memoizee
37 ```
38
39 _`memoize` name was already taken, therefore project is published as `memoizee` on NPM._
40
41 To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: [Browserify](http://browserify.org/), [Webmake](https://github.com/medikoo/modules-webmake) or [Webpack](http://webpack.github.io/)
42
43 ### Usage
44
45 ```javascript
46 var memoize = require("memoizee");
47
48 var fn = function (one, two, three) { /* ... */ };
49
50 memoized = memoize(fn);
51
52 memoized("foo", 3, "bar");
53 memoized("foo", 3, "bar"); // Cache hit
54 ```
55
56 **Note**: Invocations that throw exceptions are not cached.
57
58 ### Configuration
59
60 All below options can be applied in any combination
61
62 #### Arguments length
63
64 By default fixed number of arguments that function take is assumed (it's read from function's `length` property) this can be overridden:
65
66 ```javascript
67 memoized = memoize(fn, { length: 2 });
68
69 memoized("foo"); // Assumed: 'foo', undefined
70 memoized("foo", undefined); // Cache hit
71
72 memoized("foo", 3, {}); // Third argument is ignored (but passed to underlying function)
73 memoized("foo", 3, 13); // Cache hit
74 ```
75
76 **Note:** [Parameters predefined with default values (ES2015+ feature)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters) are not reflected in function's `length`, therefore if you want to memoize them as well, you need to tweak `length` setting accordingly
77
78 Dynamic _length_ behavior can be forced by setting _length_ to `false`, that means memoize will work with any number of arguments.
79
80 ```javascript
81 memoized = memoize(fn, { length: false });
82
83 memoized("foo");
84 memoized("foo"); // Cache hit
85 memoized("foo", undefined);
86 memoized("foo", undefined); // Cache hit
87
88 memoized("foo", 3, {});
89 memoized("foo", 3, 13);
90 memoized("foo", 3, 13); // Cache hit
91 ```
92
93 #### Primitive mode
94
95 If we work with large result sets, or memoize hot functions, default mode may not perform as fast as we expect. In that case it's good to run memoization in _primitive_ mode. To provide fast access, results are saved in hash instead of an array. Generated hash ids are result of arguments to string conversion. **Mind that this mode will work correctly only if stringified arguments produce unique strings.**
96
97 ```javascript
98 memoized = memoize(fn, { primitive: true });
99
100 memoized("/path/one");
101 memoized("/path/one"); // Cache hit
102 ```
103
104 #### Cache id resolution (normalization)
105
106 By default cache id for given call is resolved either by:
107
108 - Direct Comparison of values passed in arguments as they are. In such case two different objects, even if their characteristics is exactly same (e.g. `var a = { foo: 'bar' }, b = { foo: 'bar' }`) will be treated as two different values.
109 - Comparison of stringified values of given arguments (`primitive` mode), which serves well, when arguments are expected to be primitive values, or objects that stringify naturally do unique values (e.g. arrays)
110
111 Still above two methods do not serve all cases, e.g. if we want to memoize function where arguments are hash objects which we do not want to compare by instance but by its content.
112
113 ##### Writing custom cache id normalizers
114
115 There's a `normalizer` option through which we can pass custom cache id normalization function.
116
117 ###### Memoizing on dictionary (object hash) arguments)
118
119 if we want to memoize a function where argument is a hash object which we do not want to compare by instance but by its content, then we can achieve it as following:
120
121 ```javascript
122 var mfn = memoize(
123 function (hash) {
124 // body of memoized function
125 },
126 {
127 normalizer: function (args) {
128 // args is arguments object as accessible in memoized function
129 return JSON.stringify(args[0]);
130 },
131 }
132 );
133
134 mfn({ foo: "bar" });
135 mfn({ foo: "bar" }); // Cache hit
136 ```
137
138 If additionally we want to ensure that our logic works well with different order of properties, we need to imply an additional sorting, e.g.
139
140 ```javascript
141 const deepSortedEntries = object =>
142 Object.entries(object)
143 .map(([key, value]) => {
144 if (value && typeof value === "object") return [key, deepSortedEntries(value)];
145 return [key, value];
146 })
147 .sort();
148
149 var mfn = memoize(
150 function (hash) {
151 // body of memoized function
152 },
153 {
154 normalizer: function (args) {
155 // args is arguments object as accessible in memoized function
156 return JSON.stringify(deepSortedEntries(args[0]));
157 },
158 }
159 );
160
161 mfn({ foo: "bar", bar: "foo" });
162 mfn({ bar: "foo", foo: "bar" }); // Cache hit
163 ```
164
165 #### Argument resolvers
166
167 When we're expecting arguments of certain type it's good to coerce them before doing memoization. We can do that by passing additional resolvers array:
168
169 ```javascript
170 memoized = memoize(fn, { length: 2, resolvers: [String, Boolean] });
171
172 memoized(12, [1, 2, 3].length);
173 memoized("12", true); // Cache hit
174 memoized({ toString: function () { return "12"; } }, {}); // Cache hit
175 ```
176
177 **Note. If your arguments are collections (arrays or hashes) that you want to memoize by content (not by self objects), you need to cast them to strings**, for it's best to just use [primitive mode](#primitive-mode). Arrays have standard string representation and work with primitive mode out of a box, for hashes you need to define `toString` method, that will produce unique string descriptions, or rely on `JSON.stringify`.
178
179 Similarly **if you want to memoize functions by their code representation not by their objects, you should use primitive mode**.
180
181 #### Memoizing asynchronous functions
182
183 ##### Promise returning functions
184
185 With _promise_ option we indicate that we memoize a function that returns promise.
186
187 The difference from natural behavior is that in case when promise was rejected with exception,
188 the result is immediately removed from memoize cache, and not kept as further reusable result.
189
190 ```javascript
191 var afn = function (a, b) {
192 return new Promise(function (res) { res(a + b); });
193 };
194 memoized = memoize(afn, { promise: true });
195
196 memoized(3, 7);
197 memoized(3, 7); // Cache hit
198 ```
199
200 ###### Important notice on internal promises handling
201
202 Default handling stands purely on _then_ which has side-effect of muting eventual unhandled rejection notifications.
203 Alternatively we can other (explained below), by stating with `promise` option desired mode:
204
205 ```javascript
206 memoized = memoize(afn, { promise: "done:finally" });
207 ```
208
209 Supported modes
210
211 - `then` _(default)_. Values are resolved purely by passing callbacks to `promise.then`. **Side effect is that eventual unhandled rejection on given promise
212 come with no logged warning!**, and that to avoid implied error swallowing both states are resolved tick after callbacks were invoked
213
214 - `done` Values are resolved purely by passing callback to `done` method. **Side effect is that eventual unhandled rejection on given promise come with no logged warning!**.
215
216 - `done:finally` The only method that may work with no side-effects assuming that promise implementaion does not throw unconditionally
217 if no _onFailure_ callback was passed to `done`, and promise error was handled by other consumer (this is not commonly implemented _done_ behavior). Otherwise side-effect is that exception is thrown on promise rejection (highly not recommended)
218
219 ##### Node.js callback style functions
220
221 With _async_ option we indicate that we memoize asynchronous (Node.js style) function
222 Operations that result with an error are not cached.
223
224 ```javascript
225 afn = function (a, b, cb) {
226 setTimeout(function () { cb(null, a + b); }, 200);
227 };
228 memoized = memoize(afn, { async: true });
229
230 memoized(3, 7, function (err, res) {
231 memoized(3, 7, function (err, res) {
232 // Cache hit
233 });
234 });
235
236 memoized(3, 7, function (err, res) {
237 // Cache hit
238 });
239 ```
240
241 #### Memoizing methods
242
243 When we are defining a prototype, we may want to define a method that will memoize it's results in relation to each instance. A basic way to obtain that would be:
244
245 ```javascript
246 var Foo = function () {
247 this.bar = memoize(this.bar.bind(this), { someOption: true });
248 // ... constructor logic
249 };
250 Foo.prototype.bar = function () {
251 // ... method logic
252 };
253 ```
254
255 There's a lazy methods descriptor generator provided:
256
257 ```javascript
258 var d = require("d");
259 var memoizeMethods = require("memoizee/methods");
260
261 var Foo = function () {
262 // ... constructor logic
263 };
264 Object.defineProperties(
265 Foo.prototype,
266 memoizeMethods({
267 bar: d(
268 function () {
269 // ... method logic
270 },
271 { someOption: true }
272 ),
273 })
274 );
275 ```
276
277 #### WeakMap based configurations
278
279 In this case memoization cache is not bound to memoized function (which we may want to keep forever), but to objects for which given results were generated.
280
281 This mode works only for functions of which first argument is expected to be an object.
282 It can be combined with other options mentioned across documentation. However due to WeakMap specificity global clear is not possible.
283
284 ```javascript
285 var memoize = require("memoizee/weak");
286
287 var memoized = memoize(function (obj) { return Object.keys(obj); });
288
289 var obj = { foo: true, bar: false };
290 memoized(obj);
291 memoized(obj); // Cache hit
292 ```
293
294 #### Cache handling
295
296 ##### Manual clean up:
297
298 Delete data for particular call.
299
300 ```javascript
301 memoized.delete("foo", true);
302 ```
303
304 Arguments passed to `delete` are treated with same rules as input arguments passed to function
305
306 Clear all cached data:
307
308 ```javascript
309 memoized.clear();
310 ```
311
312 ##### Expire cache after given period of time
313
314 With _maxAge_ option we can ensure that cache for given call is cleared after predefined period of time (in milliseconds)
315
316 ```javascript
317 memoized = memoize(fn, { maxAge: 1000 }); // 1 second
318
319 memoized("foo", 3);
320 memoized("foo", 3); // Cache hit
321 setTimeout(function () {
322 memoized("foo", 3); // No longer in cache, re-executed
323 memoized("foo", 3); // Cache hit
324 }, 2000);
325 ```
326
327 Additionally we may ask to _pre-fetch_ in a background a value that is about to expire. _Pre-fetch_ is invoked only if value is accessed close to its expiry date. By default it needs to be within at least 33% of _maxAge_ timespan before expire:
328
329 ```javascript
330 memoized = memoize(fn, { maxAge: 1000, preFetch: true }); // Defaults to 0.33
331
332 memoized("foo", 3);
333 memoized("foo", 3); // Cache hit
334
335 setTimeout(function () {
336 memoized("foo", 3); // Cache hit
337 }, 500);
338
339 setTimeout(function () {
340 memoized("foo", 3); // Cache hit, silently pre-fetched in next tick
341 }, 800);
342
343 setTimeout(function () {
344 memoized("foo", 3); // Cache hit
345 }, 1300);
346 ```
347
348 _Pre-fetch_ timespan can be customized:
349
350 ```javascript
351 memoized = memoize(fn, { maxAge: 1000, preFetch: 0.6 });
352
353 memoized("foo", 3);
354 memoized("foo", 3); // Cache hit
355
356 setTimeout(function () {
357 memoized("foo", 3); // Cache hit, silently pre-fetched in next tick
358 }, 500);
359
360 setTimeout(function () {
361 memoized("foo", 3); // Cache hit
362 }, 1300);
363 ```
364
365 _Thanks [@puzrin](https://github.com/puzrin) for helpful suggestions concerning this functionality_
366
367 ##### Reference counter
368
369 We can track number of references returned from cache, and manually delete them. When the last reference is cleared, the cache is purged automatically:
370
371 ```javascript
372 memoized = memoize(fn, { refCounter: true });
373
374 memoized("foo", 3); // refs: 1
375 memoized("foo", 3); // Cache hit, refs: 2
376 memoized("foo", 3); // Cache hit, refs: 3
377 memoized.deleteRef("foo", 3); // refs: 2
378 memoized.deleteRef("foo", 3); // refs: 1
379 memoized.deleteRef("foo", 3); // refs: 0, Cache purged for 'foo', 3
380 memoized("foo", 3); // Re-executed, refs: 1
381 ```
382
383 ##### Limiting cache size
384
385 With _max_ option you can limit cache size, it's backed with [LRU algorithm](http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used), provided by low-level [lru-queue](https://github.com/medikoo/lru-queue) utility.
386
387 The _size_ relates purely to count of results we want to keep in cache, it doesn't relate to memory cost associated with cache value (but such feature is likely to be introduced with next version of memoizee).
388
389 ```javascript
390 memoized = memoize(fn, { max: 2 });
391
392 memoized("foo", 3);
393 memoized("bar", 7);
394 memoized("foo", 3); // Cache hit
395 memoized("bar", 7); // Cache hit
396 memoized("lorem", 11); // Cache cleared for 'foo', 3
397 memoized("bar", 7); // Cache hit
398 memoized("foo", 3); // Re-executed, Cache cleared for 'lorem', 11
399 memoized("lorem", 11); // Re-executed, Cache cleared for 'bar', 7
400 memoized("foo", 3); // Cache hit
401 memoized("bar", 7); // Re-executed, Cache cleared for 'lorem', 11
402 ```
403
404 ##### Registering dispose callback
405
406 You can register a callback to be called on each value removed from the cache:
407
408 ```javascript
409 memoized = memoize(fn, { dispose: function (value) { /*…*/ } });
410
411 var foo3 = memoized("foo", 3);
412 var bar7 = memoized("bar", 7);
413 memoized.clear("foo", 3); // Dispose called with foo3 value
414 memoized.clear("bar", 7); // Dispose called with bar7 value
415 ```
416
417 ### Benchmarks
418
419 Simple benchmark tests can be found in _benchmark_ folder. Currently it's just plain simple calculation of fibonacci sequences. To run it you need to install other test candidates:
420
421 $ npm install underscore lodash lru-cache secondary-cache
422
423 Example output taken under Node v0.10.35 on 2011 MBP Pro:
424
425 ```
426 Fibonacci 3000 x10:
427
428 1: 15ms Memoizee (primitive mode)
429 2: 15ms Underscore
430 3: 18ms lru-cache LRU (max: 1000)
431 4: 21ms secondary-cache LRU (max: 1000)
432 5: 37ms Lo-dash
433 6: 62ms Memoizee (primitive mode) LRU (max: 1000)
434 7: 163ms Memoizee (object mode) LRU (max: 1000)
435 8: 195ms Memoizee (object mode)
436 ```
437
438 ### Profiling & Statistics
439
440 If you want to make sure how much you benefit from memoization or just check if memoization works as expected, loading profile module will give access to all valuable information.
441
442 **Module needs to be imported before any memoization (that we want to track) is configured. Mind also that running profile module affects performance, it's best not to use it in production environment**
443
444 ```javascript
445 var memProfile = require('memoizee/profile');
446 ...
447 ...
448 memoize(fn);
449 ...
450 memoize(fn, { profileName: 'Some Function' })
451 ...
452 memoize(fn, { profileName: 'Another Function' })
453 ```
454
455 Access statistics at any time:
456
457 ```javascript
458 memProfile.statistics; // Statistics accessible for programmatic use
459 console.log(memProfile.log()); // Output statistics data in readable form
460 ```
461
462 Example console output:
463
464 ```
465 ------------------------------------------------------------
466 Memoize statistics:
467
468 Init Cache %Cache Source location
469 11604 35682 75.46 (all)
470 2112 19901 90.41 Some Function, at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:276:12
471 2108 9087 81.17 Another Function, at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:293:10
472 6687 2772 29.31 at /Users/medikoo/Projects/_packages/next/lib/fs/watch.js:125:9
473 697 3922 84.91 at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:277:15
474 ------------------------------------------------------------
475 ```
476
477 - _Init_ – Initial hits
478 - _Cache_ – Cache hits
479 - _%Cache_ – What's the percentage of cache hits (of all function calls)
480 - _Source location_ – Where in the source code given memoization was initialized
481
482 ### Tests
483
484 $ npm test
485
486 Project cross-browser compatibility to be supported by:
487
488 <a href="https://browserstack.com"><img src="https://bstacksupport.zendesk.com/attachments/token/Pj5uf2x5GU9BvWErqAr51Jh2R/?name=browserstack-logo-600x315.png" height="150" /></a>
489
490 ## Security contact information
491
492 To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
493
494 ---
495
496 <div align="center">
497 <b>
498 <a href="https://tidelift.com/subscription/pkg/npm-memoizee?utm_source=npm-memoizee&utm_medium=referral&utm_campaign=readme">Get professional support for d with a Tidelift subscription</a>
499 </b>
500 <br>
501 <sub>
502 Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
503 </sub>
504 </div>
505
506 ### Contributors
507
508 - [@puzrin](https://github.com/puzrin) (Vitaly Puzrin)
509 - Proposal and help with coining right _pre-fetch_ logic for [_maxAge_](https://github.com/medikoo/memoize#expire-cache-after-given-period-of-time) variant
510
511 [build-image]: https://github.com/medikoo/memoizee/workflows/Integrate/badge.svg
512 [build-url]: https://github.com/medikoo/memoizee/actions?query=workflow%3AIntegrate
513 [cov-image]: https://img.shields.io/codecov/c/github/medikoo/memoizee.svg
514 [cov-url]: https://codecov.io/gh/medikoo/memoizee
515 [npm-image]: https://img.shields.io/npm/v/memoizee.svg
516 [npm-url]: https://www.npmjs.com/package/memoizee