├── .editorconfig
├── .github
├── FUNDING.yml
└── workflows
│ ├── integrate.yml
│ ├── publish.yml
│ └── validate.yml
├── .gitignore
├── .npmignore
├── .testignore
├── CHANGELOG.md
├── CHANGES
├── LICENSE
├── README.md
├── benchmark
└── fibonacci.js
├── commitlint.config.js
├── ext
├── async.js
├── dispose.js
├── max-age.js
├── max.js
├── promise.js
└── ref-counter.js
├── index.js
├── lib
├── configure-map.js
├── methods.js
├── registered-extensions.js
├── resolve-length.js
├── resolve-normalize.js
├── resolve-resolve.js
└── weak.js
├── methods-plain.js
├── methods.js
├── normalizers
├── get-1.js
├── get-fixed.js
├── get-primitive-fixed.js
├── get.js
└── primitive.js
├── package.json
├── plain.js
├── profile.js
├── tea.yaml
├── test
├── ext
│ ├── async.js
│ ├── dispose.js
│ ├── max-age.js
│ ├── max.js
│ ├── promise.js
│ └── ref-counter.js
├── index.js
├── lib
│ ├── configure-map.js
│ ├── methods.js
│ ├── registered-extensions.js
│ ├── resolve-length.js
│ ├── resolve-normalize.js
│ ├── resolve-resolve.js
│ └── weak.js
├── methods-plain.js
├── methods.js
├── normalizers
│ ├── get-1.js
│ ├── get-fixed.js
│ ├── get-primitive-fixed.js
│ ├── get.js
│ └── primitive.js
├── plain.js
├── profile.js
├── weak-plain.js
└── weak.js
├── weak-plain.js
└── weak.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: http://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | [*]
7 | charset = utf-8
8 | end_of_line = lf
9 | insert_final_newline = true
10 | indent_style = tab
11 | trim_trailing_whitespace = true
12 |
13 | [*.{md,yml}]
14 | indent_size = 2
15 | indent_style = space
16 |
17 | [*.md]
18 | trim_trailing_whitespace = false
19 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: medikoo
2 | tidelift: "npm/memoizee"
3 |
--------------------------------------------------------------------------------
/.github/workflows/integrate.yml:
--------------------------------------------------------------------------------
1 | # main only
2 |
3 | name: Integrate
4 |
5 | on:
6 | push:
7 | branches: [main]
8 |
9 | env:
10 | FORCE_COLOR: 1
11 |
12 | jobs:
13 | _:
14 | uses: medikoo/github-actions-workflows/.github/workflows/0.12-integrate.yml@main
15 | secrets:
16 | USER_GITHUB_TOKEN: ${{ secrets.USER_GITHUB_TOKEN }}
17 |
--------------------------------------------------------------------------------
/.github/workflows/publish.yml:
--------------------------------------------------------------------------------
1 | # Version tags only
2 |
3 | name: Publish
4 |
5 | on:
6 | push:
7 | tags:
8 | - v[0-9]+.[0-9]+.[0-9]+
9 |
10 | env:
11 | FORCE_COLOR: 1
12 |
13 | jobs:
14 | _:
15 | uses: medikoo/github-actions-workflows/.github/workflows/publish.yml@main
16 | secrets:
17 | USER_GITHUB_TOKEN: ${{ secrets.USER_GITHUB_TOKEN }}
18 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
19 |
--------------------------------------------------------------------------------
/.github/workflows/validate.yml:
--------------------------------------------------------------------------------
1 | # PR's only
2 |
3 | name: Validate
4 |
5 | on:
6 | pull_request:
7 | branches: [main]
8 |
9 | env:
10 | FORCE_COLOR: 1
11 |
12 | jobs:
13 | _:
14 | uses: medikoo/github-actions-workflows/.github/workflows/0.12-validate.yml@main
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.nyc_output
2 | /coverage
3 | /node_modules
4 | npm-debug.log
5 | /package-lock.json
6 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | /.editorconfig
2 | /.github
3 | /.testignore
4 | /test
5 | /benchmark
6 |
--------------------------------------------------------------------------------
/.testignore:
--------------------------------------------------------------------------------
1 | /benchmark
2 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ### [0.4.17](https://github.com/medikoo/memoizee/compare/v0.4.16...v0.4.17) (2024-05-24)
6 |
7 | ### Bug Fixes
8 |
9 | - Fix node version declaration ([15ece26](https://github.com/medikoo/memoizee/commit/15ece26de3e7cc949ebe67b62e21edaa89101480))
10 |
11 | ### [0.4.16](https://github.com/medikoo/memoizee/compare/v0.4.15...v0.4.16) (2024-05-23)
12 |
13 | ### Maintenance Improvements
14 |
15 | - Prettify ([fe3e492](https://github.com/medikoo/memoizee/commit/fe3e4922a7d6b6e2a4f90b40bfeea10638b3b05b))
16 |
17 | ### [0.4.15](https://github.com/medikoo/memoizee/compare/v0.4.14...v0.4.15) (2021-01-08)
18 |
19 | _Maintainance update_
20 |
21 |
22 |
23 | ## [0.4.14](https://github.com/medikoo/memoizee/compare/v0.4.13...v0.4.14) (2018-08-13)
24 |
25 | ### Bug Fixes
26 |
27 | - ensure to not force unhandled rejections ([9b416ea](https://github.com/medikoo/memoizee/commit/9b416ea))
28 |
29 |
30 |
31 | ## [0.4.13](https://github.com/medikoo/memoizee/compare/v0.4.12...v0.4.13) (2018-08-06)
32 |
33 | ### Features
34 |
35 | - **promise:** support cancellation case ([b4b018d](https://github.com/medikoo/memoizee/commit/b4b018d)), closes [#97](https://github.com/medikoo/memoizee/issues/97)
36 |
37 |
38 |
39 | ## [0.4.12](https://github.com/medikoo/memoizee/compare/v0.4.11...v0.4.12) (2018-02-23)
40 |
41 | ### Bug Fixes
42 |
43 | - **max-age:** unref timeouts to not block processes from exiting ([5bcc5a4](https://github.com/medikoo/memoizee/commit/5bcc5a4)), closes [#25](https://github.com/medikoo/memoizee/issues/25)
44 |
45 |
46 |
47 | ## [0.4.11](https://github.com/medikoo/memoizee/compare/v0.4.10...v0.4.11) (2017-09-11)
48 |
49 | ### Bug Fixes
50 |
51 | - \_get and \_has internal args handling. ([7cb1c7a](https://github.com/medikoo/memoizee/commit/7cb1c7a)), closes [#88](https://github.com/medikoo/memoizee/issues/88)
52 |
53 |
54 |
55 | ## [0.4.10](https://github.com/medikoo/memoizee/compare/v0.4.9...v0.4.10) (2017-09-07)
56 |
57 | ### Bug Fixes
58 |
59 | - remove then:finally mode as it can't work right ([5b79698](https://github.com/medikoo/memoizee/commit/5b79698))
60 |
61 |
62 |
63 | ## [0.4.9](https://github.com/medikoo/memoizee/compare/v0.4.8...v0.4.9) (2017-08-29)
64 |
65 |
66 |
67 | ## [0.4.8](https://github.com/medikoo/memoizee/compare/v0.4.7...v0.4.8) (2017-08-29)
68 |
69 |
70 |
71 | ## [0.4.7](https://github.com/medikoo/memoizee/compare/v0.4.6...v0.4.7) (2017-08-29)
72 |
73 | ### Features
74 |
75 | - improve 'promise' mode handling ([759e315](https://github.com/medikoo/memoizee/commit/759e315))
76 | - improve internal promise validation ([d23b94f](https://github.com/medikoo/memoizee/commit/d23b94f))
77 |
78 |
79 |
80 | ## [0.4.6](https://github.com/medikoo/memoizee/compare/v0.4.5...v0.4.6) (2017-08-24)
81 |
82 | - `profileName` option for naming memoizee instances in profile output
83 |
84 |
85 |
86 | ## [0.4.5](https://github.com/medikoo/memoizee/compare/v0.4.4...v0.4.5) (2017-05-10)
87 |
88 | ### Bug Fixes
89 |
90 | - resolution of extensions with weak handling ([f29a97b](https://github.com/medikoo/memoizee/commit/f29a97b)), closes [#79](https://github.com/medikoo/memoizee/issues/79)
91 |
92 | ## Old changelog
93 |
94 | See `CHANGES`
95 |
--------------------------------------------------------------------------------
/CHANGES:
--------------------------------------------------------------------------------
1 | -- For new changelog see CHANGELOG.md
2 |
3 | v0.4.4 -- 2017.03.15
4 | * Expose _get and _has methods. It provides temporary means for better cache inspection until
5 | v1 is delivered
6 |
7 | v0.4.3 -- 2017.02.20
8 | * Fix normalization resolver, so it validates already normalized resolvers (reported at #70)
9 |
10 | v0.4.2 -- 2017.02.17
11 | * Guard proper promise resolution in promise mode
12 | * Improve documentation
13 | * Improve npm scripts configuration
14 | * Improve CI configuration
15 |
16 | v0.4.1 -- 2016.07.13
17 | * Fix promise mode to not use `then` and `finally` pair. Thanks @Kovensky
18 | * Add 'done' mode to 'promise' mode (so now callbacks can be registered through `done` but no
19 | `finally` event if it's implemented)
20 |
21 | v0.4.0 -- 2016.07.07
22 | * Introduce 'promise' mode
23 | * Change signature of internal events for 'async' case
24 | * Document 'normalizer' option
25 |
26 | v0.3.10 -- 2016.04.21
27 | * Fix resolvers bug (#12)
28 | * Fix arguments support for weak mode
29 | * Update repository address after rename
30 |
31 | v0.3.9 -- 2015.08.04
32 | * Update dependencies
33 | * Improve documentation
34 | * FIx spelling of LICENSE
35 |
36 | v0.3.8 -- 2014.10.08
37 | * Introduce WeakMap based `weak` mode
38 |
39 | v0.3.7 -- 2014.08.14
40 | * Fix prefetch support for asynchronous functions (#19)
41 | * Configure lint scripts
42 |
43 | v0.3.6 -- 2014.07.28
44 | * Fix race condition issue related to clear/delete calls and returning id's (#18)
45 | * Fix maxAge major cache handling issue (on timeout instead of individual record whole cache was
46 | cleared)
47 |
48 | v0.3.5 -- 2014.07.07
49 | * Fix internal id genaration, for primitive, length = 1 case.
50 | Ids were not serialized to strings, and that caused issues with other
51 | internal logiv, which e.g. treated `null` case specifically.
52 | Fixes #15 (Thanks @isaacg for reporting)
53 |
54 | v0.3.4 -- 2014.06.22
55 | * Fix async handling in case of clear between two async calls
56 | (assurance of unique cache ids solves that). Fixes #13
57 |
58 | v0.3.3 -- 2014.05.12
59 | * Fix profiler special property definition
60 |
61 | v0.3.2 -- 2014.05.01
62 | * Provide no-arguments memoization out of a box
63 | (no need to provide normalizer to `memoizee/plain`)
64 |
65 | v0.3.1 -- 2014.04.27
66 | * Update package.json to use latest 'tad' engine (fixes tests evaluation)
67 |
68 | v0.3.0 -- 2014.04.27
69 | Major reorganization and partial refactoring
70 | * Move out main modules from lib folder
71 | * Introduce normalizer based memoization. Primitive and regular handlers were converted into
72 | dedicated normalizers (located in lib/normalizers folder). Custom normalizers can be provided at
73 | run time via `normalizer` option.
74 | * Provide 'plain' module which does not import (require) any extensions or normalizers. Thanks to
75 | that it's lighter for e.g. client-side bundle. Any extensions that are expected to be used should
76 | be required upfront, normalizers should be provided via `normalizer` option.
77 | * Rename `memoized.clear` into `memoized.delete`, and `memoized.clearAll` into `memoized.clear`
78 | * Rename `memoized.clearRef` into `memoized.deleteRef` (applies to 'refCounter' option)
79 | * Remove 'method' option. Instead 'methods' and 'methods-plan' modules are provided which generate
80 | descriptors for lazy created memoized methods.
81 | * 'profile' is no longer an extension. It's provided as dedicated module.
82 | * Clean up logic for `async` handling
83 | * Take out 'max' extension's LRU logic into external `lru-queue` package.
84 | See https://github.com/medikoo/lru-queue
85 | * Remove possibility to access original arguments when resolvers are used
86 | * Assure expected length of memoized functions
87 | * Remove Makefile (it's environment agnostic package)
88 |
89 | v0.2.6 -- 2013.10.08
90 | * Fix internal events propagation when handling async calls that
91 | resolve with errors. `asyncpurge` was emitted for values that had no
92 | `asyncinit` emitted. Issue #9
93 |
94 | v0.2.5 -- 2013.06.21
95 | * Fix primitive handling for dynamic arguments length
96 |
97 | v0.2.4 -- 2013.03.23
98 | * Throw on circular invocations, they cannot be memoized as intended.
99 |
100 | v0.2.3 -- 2012.10.04
101 | * Fixed serious bug related to not properly cleared cache when working in
102 | regular mode
103 |
104 | v0.2.2 -- 2012.10.03
105 | * preFetch functionality for maxAge variant
106 | * Prevent memoization of already memoized functions
107 |
108 | v0.2.1 -- 2012.09.21
109 | * Fix missing global reference in method option logic
110 | * Fix variable visibility in async option logic
111 | * Lint cleanup
112 |
113 | v0.2.0 -- 2012.09.21
114 | * Modularization and general algorithm cleanup
115 | * Cache is limited (max option) using LRU instead of FIFO algorithm
116 | * Improved async mode, and its handling by other options
117 |
118 | v0.1.1 -- 2012.09.19
119 | * Fix dispose invocations for no arguments call
120 | * Small documentation improvements
121 |
122 | v0.1.0 -- 2012.09.18
123 | * Initial. Derived from es5-ext package and added `async`, `maxAge`,
124 | `refCounter`, `max` and `dispose` options.
125 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | ISC License
2 |
3 | Copyright (c) 2012-2024, Mariusz Nowak, @medikoo, medikoo.com
4 |
5 | Permission to use, copy, modify, and/or distribute this software for any
6 | purpose with or without fee is hereby granted, provided that the above
7 | copyright notice and this permission notice appear in all copies.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 | AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 | OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 | PERFORMANCE OF THIS SOFTWARE.
16 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
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 |
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 |
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
517 |
--------------------------------------------------------------------------------
/benchmark/fibonacci.js:
--------------------------------------------------------------------------------
1 | /* global console */
2 | /* eslint no-console: 0, id-length: 0 */
3 |
4 | "use strict";
5 |
6 | // Simple benchmark for very simple memoization case (fibonacci series)
7 | // To run it, do following in memoizee package path:
8 | //
9 | // $ npm install underscore lodash lru-cache secondary-cache
10 | // $ node benchmark/fibonacci.js
11 |
12 | var forEach = require("es5-ext/object/for-each")
13 | , pad = require("es5-ext/string/#/pad")
14 | , memoizee = require("..")
15 | , underscore = require("underscore").memoize
16 | , lodash = require("lodash").memoize
17 | , lruCache = require("lru-cache")
18 | , lruSecondary = require("secondary-cache/lib/lru-cache");
19 |
20 | var now = Date.now
21 | , time
22 | , getFib
23 | , lru
24 | , memo
25 | , total
26 | , index = 3000
27 | , count = 10
28 | , i
29 | , lruMax = 1000
30 | , data = {}
31 | , lruObj;
32 |
33 | getFib = function (memoize, opts) {
34 | var fib = memoize(function (x) { return x < 2 ? 1 : fib(x - 1) + fib(x - 2); }, opts);
35 | return fib;
36 | };
37 |
38 | lru = function (x) {
39 | var value = lruObj.get(x);
40 | if (value === undefined) {
41 | value = x < 2 ? 1 : lru(x - 1) + lru(x - 2);
42 | lruObj.set(x, value);
43 | }
44 | return value;
45 | };
46 |
47 | console.log("Fibonacci", index, "x" + count + ":\n");
48 |
49 | total = 0;
50 | i = count;
51 | while (i--) {
52 | memo = getFib(memoizee);
53 | time = now();
54 | memo(index);
55 | total += now() - time;
56 | }
57 | data["Memoizee (object mode)"] = total;
58 |
59 | total = 0;
60 | i = count;
61 | while (i--) {
62 | memo = getFib(memoizee, { primitive: true });
63 | time = now();
64 | memo(index);
65 | total += now() - time;
66 | }
67 | data["Memoizee (primitive mode)"] = total;
68 |
69 | total = 0;
70 | i = count;
71 | while (i--) {
72 | memo = getFib(underscore);
73 | time = now();
74 | memo(index);
75 | total += now() - time;
76 | }
77 | data.Underscore = total;
78 |
79 | total = 0;
80 | i = count;
81 | while (i--) {
82 | memo = getFib(lodash);
83 | time = now();
84 | memo(index);
85 | total += now() - time;
86 | }
87 | data["Lo-dash"] = total;
88 |
89 | total = 0;
90 | i = count;
91 | while (i--) {
92 | memo = getFib(memoizee, { primitive: true, max: lruMax });
93 | time = now();
94 | memo(index);
95 | total += now() - time;
96 | }
97 | data["Memoizee (primitive mode) LRU (max: 1000)"] = total;
98 |
99 | total = 0;
100 | i = count;
101 | while (i--) {
102 | memo = getFib(memoizee, { max: lruMax });
103 | time = now();
104 | memo(index);
105 | total += now() - time;
106 | }
107 | data["Memoizee (object mode) LRU (max: 1000)"] = total;
108 |
109 | total = 0;
110 | i = count;
111 | while (i--) {
112 | lruObj = lruCache({ max: lruMax });
113 | time = now();
114 | lru(index);
115 | total += now() - time;
116 | }
117 | data["lru-cache LRU (max: 1000)"] = total;
118 |
119 | total = 0;
120 | i = count;
121 | while (i--) {
122 | lruObj = lruSecondary(lruMax);
123 | time = now();
124 | lru(index);
125 | total += now() - time;
126 | }
127 | data["secondary-cache LRU (max: 1000)"] = total;
128 |
129 | forEach(
130 | data,
131 | function (value, name, obj, currentIndex) {
132 | console.log(currentIndex + 1 + ":", pad.call(value, " ", 5) + "ms ", name);
133 | },
134 | null,
135 | function (a, b) { return this[a] - this[b]; }
136 | );
137 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = {
4 | rules: {
5 | "body-leading-blank": [2, "always"],
6 | "body-max-line-length": [2, "always", 72],
7 | "footer-leading-blank": [2, "always"],
8 | "footer-max-line-length": [2, "always", 72],
9 | "header-max-length": [2, "always", 72],
10 | "scope-case": [2, "always", "start-case"],
11 | "scope-enum": [2, "always", [""]],
12 | "subject-case": [2, "always", "sentence-case"],
13 | "subject-empty": [2, "never"],
14 | "subject-full-stop": [2, "never", "."],
15 | "type-case": [2, "always", "lower-case"],
16 | "type-empty": [2, "never"],
17 | "type-enum": [
18 | 2, "always",
19 | ["build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "style", "test"],
20 | ],
21 | },
22 | };
23 |
--------------------------------------------------------------------------------
/ext/async.js:
--------------------------------------------------------------------------------
1 | /* eslint consistent-this: 0, no-shadow:0, no-eq-null: 0, eqeqeq: 0, no-unused-vars: 0 */
2 |
3 | // Support for asynchronous functions
4 |
5 | "use strict";
6 |
7 | var aFrom = require("es5-ext/array/from")
8 | , objectMap = require("es5-ext/object/map")
9 | , mixin = require("es5-ext/object/mixin")
10 | , defineLength = require("es5-ext/function/_define-length")
11 | , nextTick = require("next-tick");
12 |
13 | var slice = Array.prototype.slice, apply = Function.prototype.apply, create = Object.create;
14 |
15 | require("../lib/registered-extensions").async = function (tbi, conf) {
16 | var waiting = create(null)
17 | , cache = create(null)
18 | , base = conf.memoized
19 | , original = conf.original
20 | , currentCallback
21 | , currentContext
22 | , currentArgs;
23 |
24 | // Initial
25 | conf.memoized = defineLength(function (arg) {
26 | var args = arguments, last = args[args.length - 1];
27 | if (typeof last === "function") {
28 | currentCallback = last;
29 | args = slice.call(args, 0, -1);
30 | }
31 | return base.apply((currentContext = this), (currentArgs = args));
32 | }, base);
33 | try { mixin(conf.memoized, base); }
34 | catch (ignore) {}
35 |
36 | // From cache (sync)
37 | conf.on("get", function (id) {
38 | var cb, context, args;
39 | if (!currentCallback) return;
40 |
41 | // Unresolved
42 | if (waiting[id]) {
43 | if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback];
44 | else waiting[id].push(currentCallback);
45 | currentCallback = null;
46 | return;
47 | }
48 |
49 | // Resolved, assure next tick invocation
50 | cb = currentCallback;
51 | context = currentContext;
52 | args = currentArgs;
53 | currentCallback = currentContext = currentArgs = null;
54 | nextTick(function () {
55 | var data;
56 | if (hasOwnProperty.call(cache, id)) {
57 | data = cache[id];
58 | conf.emit("getasync", id, args, context);
59 | apply.call(cb, data.context, data.args);
60 | } else {
61 | // Purged in a meantime, we shouldn't rely on cached value, recall
62 | currentCallback = cb;
63 | currentContext = context;
64 | currentArgs = args;
65 | base.apply(context, args);
66 | }
67 | });
68 | });
69 |
70 | // Not from cache
71 | conf.original = function () {
72 | var args, cb, origCb, result;
73 | if (!currentCallback) return apply.call(original, this, arguments);
74 | args = aFrom(arguments);
75 | cb = function self(err) {
76 | var cb, args, id = self.id;
77 | if (id == null) {
78 | // Shouldn't happen, means async callback was called sync way
79 | nextTick(apply.bind(self, this, arguments));
80 | return undefined;
81 | }
82 | delete self.id;
83 | cb = waiting[id];
84 | delete waiting[id];
85 | if (!cb) {
86 | // Already processed,
87 | // outcome of race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb)
88 | return undefined;
89 | }
90 | args = aFrom(arguments);
91 | if (conf.has(id)) {
92 | if (err) {
93 | conf.delete(id);
94 | } else {
95 | cache[id] = { context: this, args: args };
96 | conf.emit("setasync", id, typeof cb === "function" ? 1 : cb.length);
97 | }
98 | }
99 | if (typeof cb === "function") {
100 | result = apply.call(cb, this, args);
101 | } else {
102 | cb.forEach(function (cb) { result = apply.call(cb, this, args); }, this);
103 | }
104 | return result;
105 | };
106 | origCb = currentCallback;
107 | currentCallback = currentContext = currentArgs = null;
108 | args.push(cb);
109 | result = apply.call(original, this, args);
110 | cb.cb = origCb;
111 | currentCallback = cb;
112 | return result;
113 | };
114 |
115 | // After not from cache call
116 | conf.on("set", function (id) {
117 | if (!currentCallback) {
118 | conf.delete(id);
119 | return;
120 | }
121 | if (waiting[id]) {
122 | // Race condition: asyncFn(1, cb), asyncFn.clear(), asyncFn(1, cb)
123 | if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback.cb];
124 | else waiting[id].push(currentCallback.cb);
125 | } else {
126 | waiting[id] = currentCallback.cb;
127 | }
128 | delete currentCallback.cb;
129 | currentCallback.id = id;
130 | currentCallback = null;
131 | });
132 |
133 | // On delete
134 | conf.on("delete", function (id) {
135 | var result;
136 | // If false, we don't have value yet, so we assume that intention is not
137 | // to memoize this call. After value is obtained we don't cache it but
138 | // gracefully pass to callback
139 | if (hasOwnProperty.call(waiting, id)) return;
140 | if (!cache[id]) return;
141 | result = cache[id];
142 | delete cache[id];
143 | conf.emit("deleteasync", id, slice.call(result.args, 1));
144 | });
145 |
146 | // On clear
147 | conf.on("clear", function () {
148 | var oldCache = cache;
149 | cache = create(null);
150 | conf.emit(
151 | "clearasync", objectMap(oldCache, function (data) { return slice.call(data.args, 1); })
152 | );
153 | });
154 | };
155 |
--------------------------------------------------------------------------------
/ext/dispose.js:
--------------------------------------------------------------------------------
1 | // Call dispose callback on each cache purge
2 |
3 | "use strict";
4 |
5 | var callable = require("es5-ext/object/valid-callable")
6 | , forEach = require("es5-ext/object/for-each")
7 | , extensions = require("../lib/registered-extensions")
8 | , apply = Function.prototype.apply;
9 |
10 | extensions.dispose = function (dispose, conf, options) {
11 | var del;
12 | callable(dispose);
13 | if ((options.async && extensions.async) || (options.promise && extensions.promise)) {
14 | conf.on(
15 | "deleteasync",
16 | (del = function (id, resultArray) { apply.call(dispose, null, resultArray); })
17 | );
18 | conf.on("clearasync", function (cache) {
19 | forEach(cache, function (result, id) { del(id, result); });
20 | });
21 | return;
22 | }
23 | conf.on("delete", (del = function (id, result) { dispose(result); }));
24 | conf.on("clear", function (cache) {
25 | forEach(cache, function (result, id) { del(id, result); });
26 | });
27 | };
28 |
--------------------------------------------------------------------------------
/ext/max-age.js:
--------------------------------------------------------------------------------
1 | /* eslint consistent-this: 0 */
2 |
3 | // Timeout cached values
4 |
5 | "use strict";
6 |
7 | var aFrom = require("es5-ext/array/from")
8 | , forEach = require("es5-ext/object/for-each")
9 | , nextTick = require("next-tick")
10 | , isPromise = require("is-promise")
11 | , timeout = require("timers-ext/valid-timeout")
12 | , extensions = require("../lib/registered-extensions");
13 |
14 | var noop = Function.prototype, max = Math.max, min = Math.min, create = Object.create;
15 |
16 | extensions.maxAge = function (maxAge, conf, options) {
17 | var timeouts, postfix, preFetchAge, preFetchTimeouts;
18 |
19 | maxAge = timeout(maxAge);
20 | if (!maxAge) return;
21 |
22 | timeouts = create(null);
23 | postfix =
24 | (options.async && extensions.async) || (options.promise && extensions.promise)
25 | ? "async"
26 | : "";
27 | conf.on("set" + postfix, function (id) {
28 | timeouts[id] = setTimeout(function () { conf.delete(id); }, maxAge);
29 | if (typeof timeouts[id].unref === "function") timeouts[id].unref();
30 | if (!preFetchTimeouts) return;
31 | if (preFetchTimeouts[id]) {
32 | if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]);
33 | }
34 | preFetchTimeouts[id] = setTimeout(function () {
35 | delete preFetchTimeouts[id];
36 | }, preFetchAge);
37 | if (typeof preFetchTimeouts[id].unref === "function") preFetchTimeouts[id].unref();
38 | });
39 | conf.on("delete" + postfix, function (id) {
40 | clearTimeout(timeouts[id]);
41 | delete timeouts[id];
42 | if (!preFetchTimeouts) return;
43 | if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]);
44 | delete preFetchTimeouts[id];
45 | });
46 |
47 | if (options.preFetch) {
48 | if (options.preFetch === true || isNaN(options.preFetch)) {
49 | preFetchAge = 0.333;
50 | } else {
51 | preFetchAge = max(min(Number(options.preFetch), 1), 0);
52 | }
53 | if (preFetchAge) {
54 | preFetchTimeouts = {};
55 | preFetchAge = (1 - preFetchAge) * maxAge;
56 | conf.on("get" + postfix, function (id, args, context) {
57 | if (!preFetchTimeouts[id]) {
58 | preFetchTimeouts[id] = "nextTick";
59 | nextTick(function () {
60 | var result;
61 | if (preFetchTimeouts[id] !== "nextTick") return;
62 | delete preFetchTimeouts[id];
63 | conf.delete(id);
64 | if (options.async) {
65 | args = aFrom(args);
66 | args.push(noop);
67 | }
68 | result = conf.memoized.apply(context, args);
69 | if (options.promise) {
70 | // Supress eventual error warnings
71 | if (isPromise(result)) {
72 | if (typeof result.done === "function") result.done(noop, noop);
73 | else result.then(noop, noop);
74 | }
75 | }
76 | });
77 | }
78 | });
79 | }
80 | }
81 |
82 | conf.on("clear" + postfix, function () {
83 | forEach(timeouts, function (id) { clearTimeout(id); });
84 | timeouts = {};
85 | if (preFetchTimeouts) {
86 | forEach(preFetchTimeouts, function (id) { if (id !== "nextTick") clearTimeout(id); });
87 | preFetchTimeouts = {};
88 | }
89 | });
90 | };
91 |
--------------------------------------------------------------------------------
/ext/max.js:
--------------------------------------------------------------------------------
1 | // Limit cache size, LRU (least recently used) algorithm.
2 |
3 | "use strict";
4 |
5 | var toPosInteger = require("es5-ext/number/to-pos-integer")
6 | , lruQueue = require("lru-queue")
7 | , extensions = require("../lib/registered-extensions");
8 |
9 | extensions.max = function (max, conf, options) {
10 | var postfix, queue, hit;
11 |
12 | max = toPosInteger(max);
13 | if (!max) return;
14 |
15 | queue = lruQueue(max);
16 | postfix =
17 | (options.async && extensions.async) || (options.promise && extensions.promise)
18 | ? "async"
19 | : "";
20 |
21 | conf.on(
22 | "set" + postfix,
23 | (hit = function (id) {
24 | id = queue.hit(id);
25 | if (id === undefined) return;
26 | conf.delete(id);
27 | })
28 | );
29 | conf.on("get" + postfix, hit);
30 | conf.on("delete" + postfix, queue.delete);
31 | conf.on("clear" + postfix, queue.clear);
32 | };
33 |
--------------------------------------------------------------------------------
/ext/promise.js:
--------------------------------------------------------------------------------
1 | /* eslint max-statements: 0 */
2 |
3 | // Support for functions returning promise
4 |
5 | "use strict";
6 |
7 | var objectMap = require("es5-ext/object/map")
8 | , primitiveSet = require("es5-ext/object/primitive-set")
9 | , ensureString = require("es5-ext/object/validate-stringifiable-value")
10 | , toShortString = require("es5-ext/to-short-string-representation")
11 | , isPromise = require("is-promise")
12 | , nextTick = require("next-tick");
13 |
14 | var create = Object.create
15 | , supportedModes = primitiveSet("then", "then:finally", "done", "done:finally");
16 |
17 | require("../lib/registered-extensions").promise = function (mode, conf) {
18 | var waiting = create(null), cache = create(null), promises = create(null);
19 |
20 | if (mode === true) {
21 | mode = null;
22 | } else {
23 | mode = ensureString(mode);
24 | if (!supportedModes[mode]) {
25 | throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode");
26 | }
27 | }
28 |
29 | // After not from cache call
30 | conf.on("set", function (id, ignore, promise) {
31 | var isFailed = false;
32 |
33 | if (!isPromise(promise)) {
34 | // Non promise result
35 | cache[id] = promise;
36 | conf.emit("setasync", id, 1);
37 | return;
38 | }
39 | waiting[id] = 1;
40 | promises[id] = promise;
41 | var onSuccess = function (result) {
42 | var count = waiting[id];
43 | if (isFailed) {
44 | throw new Error(
45 | "Memoizee error: Detected unordered then|done & finally resolution, which " +
46 | "in turn makes proper detection of success/failure impossible (when in " +
47 | "'done:finally' mode)\n" +
48 | "Consider to rely on 'then' or 'done' mode instead."
49 | );
50 | }
51 | if (!count) return; // Deleted from cache before resolved
52 | delete waiting[id];
53 | cache[id] = result;
54 | conf.emit("setasync", id, count);
55 | };
56 | var onFailure = function () {
57 | isFailed = true;
58 | if (!waiting[id]) return; // Deleted from cache (or succeed in case of finally)
59 | delete waiting[id];
60 | delete promises[id];
61 | conf.delete(id);
62 | };
63 |
64 | var resolvedMode = mode;
65 | if (!resolvedMode) resolvedMode = "then";
66 |
67 | if (resolvedMode === "then") {
68 | var nextTickFailure = function () { nextTick(onFailure); };
69 | // Eventual finally needs to be attached to non rejected promise
70 | // (so we not force propagation of unhandled rejection)
71 | promise = promise.then(function (result) {
72 | nextTick(onSuccess.bind(this, result));
73 | }, nextTickFailure);
74 | // If `finally` is a function we attach to it to remove cancelled promises.
75 | if (typeof promise.finally === "function") {
76 | promise.finally(nextTickFailure);
77 | }
78 | } else if (resolvedMode === "done") {
79 | // Not recommended, as it may mute any eventual "Unhandled error" events
80 | if (typeof promise.done !== "function") {
81 | throw new Error(
82 | "Memoizee error: Retrieved promise does not implement 'done' " +
83 | "in 'done' mode"
84 | );
85 | }
86 | promise.done(onSuccess, onFailure);
87 | } else if (resolvedMode === "done:finally") {
88 | // The only mode with no side effects assuming library does not throw unconditionally
89 | // for rejected promises.
90 | if (typeof promise.done !== "function") {
91 | throw new Error(
92 | "Memoizee error: Retrieved promise does not implement 'done' " +
93 | "in 'done:finally' mode"
94 | );
95 | }
96 | if (typeof promise.finally !== "function") {
97 | throw new Error(
98 | "Memoizee error: Retrieved promise does not implement 'finally' " +
99 | "in 'done:finally' mode"
100 | );
101 | }
102 | promise.done(onSuccess);
103 | promise.finally(onFailure);
104 | }
105 | });
106 |
107 | // From cache (sync)
108 | conf.on("get", function (id, args, context) {
109 | var promise;
110 | if (waiting[id]) {
111 | ++waiting[id]; // Still waiting
112 | return;
113 | }
114 | promise = promises[id];
115 | var emit = function () { conf.emit("getasync", id, args, context); };
116 | if (isPromise(promise)) {
117 | if (typeof promise.done === "function") promise.done(emit);
118 | else {
119 | promise.then(function () { nextTick(emit); });
120 | }
121 | } else {
122 | emit();
123 | }
124 | });
125 |
126 | // On delete
127 | conf.on("delete", function (id) {
128 | delete promises[id];
129 | if (waiting[id]) {
130 | delete waiting[id];
131 | return; // Not yet resolved
132 | }
133 | if (!hasOwnProperty.call(cache, id)) return;
134 | var result = cache[id];
135 | delete cache[id];
136 | conf.emit("deleteasync", id, [result]);
137 | });
138 |
139 | // On clear
140 | conf.on("clear", function () {
141 | var oldCache = cache;
142 | cache = create(null);
143 | waiting = create(null);
144 | promises = create(null);
145 | conf.emit("clearasync", objectMap(oldCache, function (data) { return [data]; }));
146 | });
147 | };
148 |
--------------------------------------------------------------------------------
/ext/ref-counter.js:
--------------------------------------------------------------------------------
1 | // Reference counter, useful for garbage collector like functionality
2 |
3 | "use strict";
4 |
5 | var d = require("d")
6 | , extensions = require("../lib/registered-extensions")
7 | , create = Object.create
8 | , defineProperties = Object.defineProperties;
9 |
10 | extensions.refCounter = function (ignore, conf, options) {
11 | var cache, postfix;
12 |
13 | cache = create(null);
14 | postfix =
15 | (options.async && extensions.async) || (options.promise && extensions.promise)
16 | ? "async"
17 | : "";
18 |
19 | conf.on("set" + postfix, function (id, length) { cache[id] = length || 1; });
20 | conf.on("get" + postfix, function (id) { ++cache[id]; });
21 | conf.on("delete" + postfix, function (id) { delete cache[id]; });
22 | conf.on("clear" + postfix, function () { cache = {}; });
23 |
24 | defineProperties(conf.memoized, {
25 | deleteRef: d(function () {
26 | var id = conf.get(arguments);
27 | if (id === null) return null;
28 | if (!cache[id]) return null;
29 | if (!--cache[id]) {
30 | conf.delete(id);
31 | return true;
32 | }
33 | return false;
34 | }),
35 | getRefCount: d(function () {
36 | var id = conf.get(arguments);
37 | if (id === null) return 0;
38 | if (!cache[id]) return 0;
39 | return cache[id];
40 | }),
41 | });
42 | };
43 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var normalizeOpts = require("es5-ext/object/normalize-options")
4 | , resolveLength = require("./lib/resolve-length")
5 | , plain = require("./plain");
6 |
7 | module.exports = function (fn/*, options*/) {
8 | var options = normalizeOpts(arguments[1]), length;
9 |
10 | if (!options.normalizer) {
11 | length = options.length = resolveLength(options.length, fn.length, options.async);
12 | if (length !== 0) {
13 | if (options.primitive) {
14 | if (length === false) {
15 | options.normalizer = require("./normalizers/primitive");
16 | } else if (length > 1) {
17 | options.normalizer = require("./normalizers/get-primitive-fixed")(length);
18 | }
19 | } else if (length === false) options.normalizer = require("./normalizers/get")();
20 | else if (length === 1) options.normalizer = require("./normalizers/get-1")();
21 | else options.normalizer = require("./normalizers/get-fixed")(length);
22 | }
23 | }
24 |
25 | // Assure extensions
26 | if (options.async) require("./ext/async");
27 | if (options.promise) require("./ext/promise");
28 | if (options.dispose) require("./ext/dispose");
29 | if (options.maxAge) require("./ext/max-age");
30 | if (options.max) require("./ext/max");
31 | if (options.refCounter) require("./ext/ref-counter");
32 |
33 | return plain(fn, options);
34 | };
35 |
--------------------------------------------------------------------------------
/lib/configure-map.js:
--------------------------------------------------------------------------------
1 | /* eslint no-eq-null: 0, eqeqeq: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var customError = require("es5-ext/error/custom")
6 | , defineLength = require("es5-ext/function/_define-length")
7 | , d = require("d")
8 | , ee = require("event-emitter").methods
9 | , resolveResolve = require("./resolve-resolve")
10 | , resolveNormalize = require("./resolve-normalize");
11 |
12 | var apply = Function.prototype.apply
13 | , call = Function.prototype.call
14 | , create = Object.create
15 | , defineProperties = Object.defineProperties
16 | , on = ee.on
17 | , emit = ee.emit;
18 |
19 | module.exports = function (original, length, options) {
20 | var cache = create(null)
21 | , conf
22 | , memLength
23 | , get
24 | , set
25 | , del
26 | , clear
27 | , extDel
28 | , extGet
29 | , extHas
30 | , normalizer
31 | , getListeners
32 | , setListeners
33 | , deleteListeners
34 | , memoized
35 | , resolve;
36 | if (length !== false) memLength = length;
37 | else if (isNaN(original.length)) memLength = 1;
38 | else memLength = original.length;
39 |
40 | if (options.normalizer) {
41 | normalizer = resolveNormalize(options.normalizer);
42 | get = normalizer.get;
43 | set = normalizer.set;
44 | del = normalizer.delete;
45 | clear = normalizer.clear;
46 | }
47 | if (options.resolvers != null) resolve = resolveResolve(options.resolvers);
48 |
49 | if (get) {
50 | memoized = defineLength(function (arg) {
51 | var id, result, args = arguments;
52 | if (resolve) args = resolve(args);
53 | id = get(args);
54 | if (id !== null) {
55 | if (hasOwnProperty.call(cache, id)) {
56 | if (getListeners) conf.emit("get", id, args, this);
57 | return cache[id];
58 | }
59 | }
60 | if (args.length === 1) result = call.call(original, this, args[0]);
61 | else result = apply.call(original, this, args);
62 | if (id === null) {
63 | id = get(args);
64 | if (id !== null) throw customError("Circular invocation", "CIRCULAR_INVOCATION");
65 | id = set(args);
66 | } else if (hasOwnProperty.call(cache, id)) {
67 | throw customError("Circular invocation", "CIRCULAR_INVOCATION");
68 | }
69 | cache[id] = result;
70 | if (setListeners) conf.emit("set", id, null, result);
71 | return result;
72 | }, memLength);
73 | } else if (length === 0) {
74 | memoized = function () {
75 | var result;
76 | if (hasOwnProperty.call(cache, "data")) {
77 | if (getListeners) conf.emit("get", "data", arguments, this);
78 | return cache.data;
79 | }
80 | if (arguments.length) result = apply.call(original, this, arguments);
81 | else result = call.call(original, this);
82 | if (hasOwnProperty.call(cache, "data")) {
83 | throw customError("Circular invocation", "CIRCULAR_INVOCATION");
84 | }
85 | cache.data = result;
86 | if (setListeners) conf.emit("set", "data", null, result);
87 | return result;
88 | };
89 | } else {
90 | memoized = function (arg) {
91 | var result, args = arguments, id;
92 | if (resolve) args = resolve(arguments);
93 | id = String(args[0]);
94 | if (hasOwnProperty.call(cache, id)) {
95 | if (getListeners) conf.emit("get", id, args, this);
96 | return cache[id];
97 | }
98 | if (args.length === 1) result = call.call(original, this, args[0]);
99 | else result = apply.call(original, this, args);
100 | if (hasOwnProperty.call(cache, id)) {
101 | throw customError("Circular invocation", "CIRCULAR_INVOCATION");
102 | }
103 | cache[id] = result;
104 | if (setListeners) conf.emit("set", id, null, result);
105 | return result;
106 | };
107 | }
108 | conf = {
109 | original: original,
110 | memoized: memoized,
111 | profileName: options.profileName,
112 | get: function (args) {
113 | if (resolve) args = resolve(args);
114 | if (get) return get(args);
115 | return String(args[0]);
116 | },
117 | has: function (id) { return hasOwnProperty.call(cache, id); },
118 | delete: function (id) {
119 | var result;
120 | if (!hasOwnProperty.call(cache, id)) return;
121 | if (del) del(id);
122 | result = cache[id];
123 | delete cache[id];
124 | if (deleteListeners) conf.emit("delete", id, result);
125 | },
126 | clear: function () {
127 | var oldCache = cache;
128 | if (clear) clear();
129 | cache = create(null);
130 | conf.emit("clear", oldCache);
131 | },
132 | on: function (type, listener) {
133 | if (type === "get") getListeners = true;
134 | else if (type === "set") setListeners = true;
135 | else if (type === "delete") deleteListeners = true;
136 | return on.call(this, type, listener);
137 | },
138 | emit: emit,
139 | updateEnv: function () { original = conf.original; },
140 | };
141 | if (get) {
142 | extDel = defineLength(function (arg) {
143 | var id, args = arguments;
144 | if (resolve) args = resolve(args);
145 | id = get(args);
146 | if (id === null) return;
147 | conf.delete(id);
148 | }, memLength);
149 | } else if (length === 0) {
150 | extDel = function () { return conf.delete("data"); };
151 | } else {
152 | extDel = function (arg) {
153 | if (resolve) arg = resolve(arguments)[0];
154 | return conf.delete(arg);
155 | };
156 | }
157 | extGet = defineLength(function () {
158 | var id, args = arguments;
159 | if (length === 0) return cache.data;
160 | if (resolve) args = resolve(args);
161 | if (get) id = get(args);
162 | else id = String(args[0]);
163 | return cache[id];
164 | });
165 | extHas = defineLength(function () {
166 | var id, args = arguments;
167 | if (length === 0) return conf.has("data");
168 | if (resolve) args = resolve(args);
169 | if (get) id = get(args);
170 | else id = String(args[0]);
171 | if (id === null) return false;
172 | return conf.has(id);
173 | });
174 | defineProperties(memoized, {
175 | __memoized__: d(true),
176 | delete: d(extDel),
177 | clear: d(conf.clear),
178 | _get: d(extGet),
179 | _has: d(extHas),
180 | });
181 | return conf;
182 | };
183 |
--------------------------------------------------------------------------------
/lib/methods.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var forEach = require("es5-ext/object/for-each")
4 | , normalizeOpts = require("es5-ext/object/normalize-options")
5 | , callable = require("es5-ext/object/valid-callable")
6 | , lazy = require("d/lazy")
7 | , resolveLength = require("./resolve-length")
8 | , extensions = require("./registered-extensions");
9 |
10 | module.exports = function (memoize) {
11 | return function (props) {
12 | forEach(props, function (desc) {
13 | var fn = callable(desc.value), length;
14 | desc.value = function (options) {
15 | if (options.getNormalizer) {
16 | options = normalizeOpts(options);
17 | if (length === undefined) {
18 | length = resolveLength(
19 | options.length, fn.length, options.async && extensions.async
20 | );
21 | }
22 | options.normalizer = options.getNormalizer(length);
23 | delete options.getNormalizer;
24 | }
25 | return memoize(fn.bind(this), options);
26 | };
27 | });
28 | return lazy(props);
29 | };
30 | };
31 |
--------------------------------------------------------------------------------
/lib/registered-extensions.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
--------------------------------------------------------------------------------
/lib/resolve-length.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var toPosInt = require("es5-ext/number/to-pos-integer");
4 |
5 | module.exports = function (optsLength, fnLength, isAsync) {
6 | var length;
7 | if (isNaN(optsLength)) {
8 | length = fnLength;
9 | if (!(length >= 0)) return 1;
10 | if (isAsync && length) return length - 1;
11 | return length;
12 | }
13 | if (optsLength === false) return false;
14 | return toPosInt(optsLength);
15 | };
16 |
--------------------------------------------------------------------------------
/lib/resolve-normalize.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var callable = require("es5-ext/object/valid-callable");
4 |
5 | module.exports = function (userNormalizer) {
6 | var normalizer;
7 | if (typeof userNormalizer === "function") return { set: userNormalizer, get: userNormalizer };
8 | normalizer = { get: callable(userNormalizer.get) };
9 | if (userNormalizer.set !== undefined) {
10 | normalizer.set = callable(userNormalizer.set);
11 | if (userNormalizer.delete) normalizer.delete = callable(userNormalizer.delete);
12 | if (userNormalizer.clear) normalizer.clear = callable(userNormalizer.clear);
13 | return normalizer;
14 | }
15 | normalizer.set = normalizer.get;
16 | return normalizer;
17 | };
18 |
--------------------------------------------------------------------------------
/lib/resolve-resolve.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var toArray = require("es5-ext/array/to-array")
4 | , isValue = require("es5-ext/object/is-value")
5 | , callable = require("es5-ext/object/valid-callable");
6 |
7 | var slice = Array.prototype.slice, resolveArgs;
8 |
9 | resolveArgs = function (args) {
10 | return this.map(function (resolve, i) { return resolve ? resolve(args[i]) : args[i]; }).concat(
11 | slice.call(args, this.length)
12 | );
13 | };
14 |
15 | module.exports = function (resolvers) {
16 | resolvers = toArray(resolvers);
17 | resolvers.forEach(function (resolve) { if (isValue(resolve)) callable(resolve); });
18 | return resolveArgs.bind(resolvers);
19 | };
20 |
--------------------------------------------------------------------------------
/lib/weak.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var customError = require("es5-ext/error/custom")
4 | , defineLength = require("es5-ext/function/_define-length")
5 | , partial = require("es5-ext/function/#/partial")
6 | , copy = require("es5-ext/object/copy")
7 | , normalizeOpts = require("es5-ext/object/normalize-options")
8 | , callable = require("es5-ext/object/valid-callable")
9 | , d = require("d")
10 | , WeakMap = require("es6-weak-map")
11 | , resolveLength = require("./resolve-length")
12 | , extensions = require("./registered-extensions")
13 | , resolveResolve = require("./resolve-resolve")
14 | , resolveNormalize = require("./resolve-normalize");
15 |
16 | var slice = Array.prototype.slice, defineProperties = Object.defineProperties;
17 |
18 | module.exports = function (memoize) {
19 | return function (fn/*, options*/) {
20 | var map, length, options = normalizeOpts(arguments[1]), memoized, resolve, normalizer;
21 |
22 | callable(fn);
23 |
24 | // Do not memoize already memoized function
25 | if (hasOwnProperty.call(fn, "__memoized__") && !options.force) return fn;
26 |
27 | length = resolveLength(options.length, fn.length, options.async && extensions.async);
28 | options.length = length ? length - 1 : 0;
29 | map = new WeakMap();
30 |
31 | if (options.resolvers) resolve = resolveResolve(options.resolvers);
32 | if (options.normalizer) normalizer = resolveNormalize(options.normalizer);
33 |
34 | if (
35 | length === 1 &&
36 | !normalizer &&
37 | !options.async &&
38 | !options.dispose &&
39 | !options.maxAge &&
40 | !options.max &&
41 | !options.refCounter
42 | ) {
43 | return defineProperties(
44 | function (obj) {
45 | var result, args = arguments;
46 | if (resolve) args = resolve(args);
47 | obj = args[0];
48 | if (map.has(obj)) return map.get(obj);
49 | result = fn.apply(this, args);
50 | if (map.has(obj)) {
51 | throw customError("Circular invocation", "CIRCULAR_INVOCATION");
52 | }
53 | map.set(obj, result);
54 | return result;
55 | },
56 | {
57 | __memoized__: d(true),
58 | delete: d(function (obj) {
59 | if (resolve) obj = resolve(arguments)[0];
60 | return map.delete(obj);
61 | }),
62 | }
63 | );
64 | }
65 | memoized = defineProperties(
66 | defineLength(function (obj) {
67 | var memoizer, args = arguments;
68 | if (resolve) {
69 | args = resolve(args);
70 | obj = args[0];
71 | }
72 | memoizer = map.get(obj);
73 | if (!memoizer) {
74 | if (normalizer) {
75 | options = copy(options);
76 | options.normalizer = copy(normalizer);
77 | options.normalizer.get = partial.call(options.normalizer.get, obj);
78 | options.normalizer.set = partial.call(options.normalizer.set, obj);
79 | if (options.normalizer.delete) {
80 | options.normalizer.delete = partial.call(
81 | options.normalizer.delete, obj
82 | );
83 | }
84 | }
85 | map.set(obj, (memoizer = memoize(partial.call(fn, obj), options)));
86 | }
87 | return memoizer.apply(this, slice.call(args, 1));
88 | }, length),
89 | {
90 | __memoized__: d(true),
91 | delete: d(
92 | defineLength(function (obj) {
93 | var memoizer, args = arguments;
94 | if (resolve) {
95 | args = resolve(args);
96 | obj = args[0];
97 | }
98 | memoizer = map.get(obj);
99 | if (!memoizer) return;
100 | memoizer.delete.apply(this, slice.call(args, 1));
101 | }, length)
102 | ),
103 | }
104 | );
105 | if (!options.refCounter) return memoized;
106 | defineProperties(memoized, {
107 | deleteRef: d(
108 | defineLength(function (obj) {
109 | var memoizer, args = arguments;
110 | if (resolve) {
111 | args = resolve(args);
112 | obj = args[0];
113 | }
114 | memoizer = map.get(obj);
115 | if (!memoizer) return null;
116 | return memoizer.deleteRef.apply(this, slice.call(args, 1));
117 | }, length)
118 | ),
119 | getRefCount: d(
120 | defineLength(function (obj) {
121 | var memoizer, args = arguments;
122 | if (resolve) {
123 | args = resolve(args);
124 | obj = args[0];
125 | }
126 | memoizer = map.get(obj);
127 | if (!memoizer) return 0;
128 | return memoizer.getRefCount.apply(this, slice.call(args, 1));
129 | }, length)
130 | ),
131 | });
132 | return memoized;
133 | };
134 | };
135 |
--------------------------------------------------------------------------------
/methods-plain.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = require("./lib/methods")(require("./plain"));
4 |
--------------------------------------------------------------------------------
/methods.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = require("./lib/methods")(require("./"));
4 |
--------------------------------------------------------------------------------
/normalizers/get-1.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var indexOf = require("es5-ext/array/#/e-index-of");
4 |
5 | module.exports = function () {
6 | var lastId = 0, argsMap = [], cache = [];
7 | return {
8 | get: function (args) {
9 | var index = indexOf.call(argsMap, args[0]);
10 | return index === -1 ? null : cache[index];
11 | },
12 | set: function (args) {
13 | argsMap.push(args[0]);
14 | cache.push(++lastId);
15 | return lastId;
16 | },
17 | delete: function (id) {
18 | var index = indexOf.call(cache, id);
19 | if (index !== -1) {
20 | argsMap.splice(index, 1);
21 | cache.splice(index, 1);
22 | }
23 | },
24 | clear: function () {
25 | argsMap = [];
26 | cache = [];
27 | },
28 | };
29 | };
30 |
--------------------------------------------------------------------------------
/normalizers/get-fixed.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var indexOf = require("es5-ext/array/#/e-index-of")
4 | , create = Object.create;
5 |
6 | module.exports = function (length) {
7 | var lastId = 0, map = [[], []], cache = create(null);
8 | return {
9 | get: function (args) {
10 | var index = 0, set = map, i;
11 | while (index < length - 1) {
12 | i = indexOf.call(set[0], args[index]);
13 | if (i === -1) return null;
14 | set = set[1][i];
15 | ++index;
16 | }
17 | i = indexOf.call(set[0], args[index]);
18 | if (i === -1) return null;
19 | return set[1][i] || null;
20 | },
21 | set: function (args) {
22 | var index = 0, set = map, i;
23 | while (index < length - 1) {
24 | i = indexOf.call(set[0], args[index]);
25 | if (i === -1) {
26 | i = set[0].push(args[index]) - 1;
27 | set[1].push([[], []]);
28 | }
29 | set = set[1][i];
30 | ++index;
31 | }
32 | i = indexOf.call(set[0], args[index]);
33 | if (i === -1) {
34 | i = set[0].push(args[index]) - 1;
35 | }
36 | set[1][i] = ++lastId;
37 | cache[lastId] = args;
38 | return lastId;
39 | },
40 | delete: function (id) {
41 | var index = 0, set = map, i, path = [], args = cache[id];
42 | while (index < length - 1) {
43 | i = indexOf.call(set[0], args[index]);
44 | if (i === -1) {
45 | return;
46 | }
47 | path.push(set, i);
48 | set = set[1][i];
49 | ++index;
50 | }
51 | i = indexOf.call(set[0], args[index]);
52 | if (i === -1) {
53 | return;
54 | }
55 | id = set[1][i];
56 | set[0].splice(i, 1);
57 | set[1].splice(i, 1);
58 | while (!set[0].length && path.length) {
59 | i = path.pop();
60 | set = path.pop();
61 | set[0].splice(i, 1);
62 | set[1].splice(i, 1);
63 | }
64 | delete cache[id];
65 | },
66 | clear: function () {
67 | map = [[], []];
68 | cache = create(null);
69 | },
70 | };
71 | };
72 |
--------------------------------------------------------------------------------
/normalizers/get-primitive-fixed.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = function (length) {
4 | if (!length) {
5 | return function () { return ""; };
6 | }
7 | return function (args) {
8 | var id = String(args[0]), i = 0, currentLength = length;
9 | while (--currentLength) {
10 | id += "\u0001" + args[++i];
11 | }
12 | return id;
13 | };
14 | };
15 |
--------------------------------------------------------------------------------
/normalizers/get.js:
--------------------------------------------------------------------------------
1 | /* eslint max-statements: 0 */
2 |
3 | "use strict";
4 |
5 | var indexOf = require("es5-ext/array/#/e-index-of");
6 |
7 | var create = Object.create;
8 |
9 | module.exports = function () {
10 | var lastId = 0, map = [], cache = create(null);
11 | return {
12 | get: function (args) {
13 | var index = 0, set = map, i, length = args.length;
14 | if (length === 0) return set[length] || null;
15 | if ((set = set[length])) {
16 | while (index < length - 1) {
17 | i = indexOf.call(set[0], args[index]);
18 | if (i === -1) return null;
19 | set = set[1][i];
20 | ++index;
21 | }
22 | i = indexOf.call(set[0], args[index]);
23 | if (i === -1) return null;
24 | return set[1][i] || null;
25 | }
26 | return null;
27 | },
28 | set: function (args) {
29 | var index = 0, set = map, i, length = args.length;
30 | if (length === 0) {
31 | set[length] = ++lastId;
32 | } else {
33 | if (!set[length]) {
34 | set[length] = [[], []];
35 | }
36 | set = set[length];
37 | while (index < length - 1) {
38 | i = indexOf.call(set[0], args[index]);
39 | if (i === -1) {
40 | i = set[0].push(args[index]) - 1;
41 | set[1].push([[], []]);
42 | }
43 | set = set[1][i];
44 | ++index;
45 | }
46 | i = indexOf.call(set[0], args[index]);
47 | if (i === -1) {
48 | i = set[0].push(args[index]) - 1;
49 | }
50 | set[1][i] = ++lastId;
51 | }
52 | cache[lastId] = args;
53 | return lastId;
54 | },
55 | delete: function (id) {
56 | var index = 0, set = map, i, args = cache[id], length = args.length, path = [];
57 | if (length === 0) {
58 | delete set[length];
59 | } else if ((set = set[length])) {
60 | while (index < length - 1) {
61 | i = indexOf.call(set[0], args[index]);
62 | if (i === -1) {
63 | return;
64 | }
65 | path.push(set, i);
66 | set = set[1][i];
67 | ++index;
68 | }
69 | i = indexOf.call(set[0], args[index]);
70 | if (i === -1) {
71 | return;
72 | }
73 | id = set[1][i];
74 | set[0].splice(i, 1);
75 | set[1].splice(i, 1);
76 | while (!set[0].length && path.length) {
77 | i = path.pop();
78 | set = path.pop();
79 | set[0].splice(i, 1);
80 | set[1].splice(i, 1);
81 | }
82 | }
83 | delete cache[id];
84 | },
85 | clear: function () {
86 | map = [];
87 | cache = create(null);
88 | },
89 | };
90 | };
91 |
--------------------------------------------------------------------------------
/normalizers/primitive.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = function (args) {
4 | var id, i, length = args.length;
5 | if (!length) return "\u0002";
6 | id = String(args[(i = 0)]);
7 | while (--length) id += "\u0001" + args[++i];
8 | return id;
9 | };
10 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "memoizee",
3 | "version": "0.4.17",
4 | "description": "Memoize/cache function results",
5 | "author": "Mariusz Nowak (http://www.medikoo.com/)",
6 | "keywords": [
7 | "memoize",
8 | "memoizer",
9 | "cache",
10 | "memoization",
11 | "memo",
12 | "memcached",
13 | "hashing.",
14 | "storage",
15 | "caching",
16 | "memory",
17 | "gc",
18 | "weak",
19 | "garbage",
20 | "collector",
21 | "async"
22 | ],
23 | "repository": "medikoo/memoizee",
24 | "dependencies": {
25 | "d": "^1.0.2",
26 | "es5-ext": "^0.10.64",
27 | "es6-weak-map": "^2.0.3",
28 | "event-emitter": "^0.3.5",
29 | "is-promise": "^2.2.2",
30 | "lru-queue": "^0.1.0",
31 | "next-tick": "^1.1.0",
32 | "timers-ext": "^0.1.7"
33 | },
34 | "devDependencies": {
35 | "bluebird": "^3.7.2",
36 | "eslint": "^8.57.0",
37 | "eslint-config-medikoo": "^4.2.0",
38 | "git-list-updated": "^1.2.1",
39 | "github-release-from-cc-changelog": "^2.3.0",
40 | "husky": "^4.3.8",
41 | "lint-staged": "^15.2.4",
42 | "nyc": "^15.1.0",
43 | "plain-promise": "^0.1.1",
44 | "prettier-elastic": "^3.2.5",
45 | "tad": "^3.1.1"
46 | },
47 | "husky": {
48 | "hooks": {
49 | "pre-commit": "lint-staged"
50 | }
51 | },
52 | "lint-staged": {
53 | "*.js": [
54 | "eslint"
55 | ],
56 | "*.{css,html,js,json,md,yaml,yml}": [
57 | "prettier -c"
58 | ]
59 | },
60 | "eslintConfig": {
61 | "extends": "medikoo/es5",
62 | "root": true,
63 | "globals": {
64 | "setTimeout": true,
65 | "clearTimeout": true
66 | },
67 | "rules": {
68 | "max-lines-per-function": "off"
69 | }
70 | },
71 | "nyc": {
72 | "all": true,
73 | "exclude": [
74 | ".github",
75 | "coverage/**",
76 | "test/**",
77 | "*.config.js"
78 | ],
79 | "reporter": [
80 | "lcov",
81 | "html",
82 | "text-summary"
83 | ]
84 | },
85 | "prettier": {
86 | "printWidth": 100,
87 | "tabWidth": 4,
88 | "overrides": [
89 | {
90 | "files": [
91 | "*.md",
92 | "*.yml"
93 | ],
94 | "options": {
95 | "tabWidth": 2
96 | }
97 | }
98 | ]
99 | },
100 | "scripts": {
101 | "coverage": "nyc npm test",
102 | "lint": "eslint --ignore-path=.gitignore .",
103 | "lint:updated": "pipe-git-updated --base=main --ext=js -- eslint --ignore-pattern '!*'",
104 | "prettier-check": "prettier -c --ignore-path .gitignore \"**/*.{css,html,js,json,md,yaml,yml}\"",
105 | "prettier-check:updated": "pipe-git-updated --base=main --ext=css --ext=html --ext=js --ext=json --ext=md --ext=yaml --ext=yml -- prettier -c",
106 | "prettify": "prettier --write --ignore-path .gitignore \"**/*.{css,html,js,json,md,yaml,yml}\"",
107 | "prettify:updated": "pipe-git-updated ---base=main -ext=css --ext=html --ext=js --ext=json --ext=md --ext=yaml --ext=yml -- prettier --write",
108 | "test": "tad"
109 | },
110 | "engines": {
111 | "node": ">=0.12"
112 | },
113 | "license": "ISC"
114 | }
115 |
--------------------------------------------------------------------------------
/plain.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var callable = require("es5-ext/object/valid-callable")
4 | , forEach = require("es5-ext/object/for-each")
5 | , extensions = require("./lib/registered-extensions")
6 | , configure = require("./lib/configure-map")
7 | , resolveLength = require("./lib/resolve-length");
8 |
9 | module.exports = function self(fn/*, options */) {
10 | var options, length, conf;
11 |
12 | callable(fn);
13 | options = Object(arguments[1]);
14 |
15 | if (options.async && options.promise) {
16 | throw new Error("Options 'async' and 'promise' cannot be used together");
17 | }
18 |
19 | // Do not memoize already memoized function
20 | if (hasOwnProperty.call(fn, "__memoized__") && !options.force) return fn;
21 |
22 | // Resolve length;
23 | length = resolveLength(options.length, fn.length, options.async && extensions.async);
24 |
25 | // Configure cache map
26 | conf = configure(fn, length, options);
27 |
28 | // Bind eventual extensions
29 | forEach(extensions, function (extFn, name) {
30 | if (options[name]) extFn(options[name], conf, options);
31 | });
32 |
33 | if (self.__profiler__) self.__profiler__(conf);
34 |
35 | conf.updateEnv();
36 | return conf.memoized;
37 | };
38 |
--------------------------------------------------------------------------------
/profile.js:
--------------------------------------------------------------------------------
1 | // Gathers statistical data, and provides them in convinient form
2 |
3 | "use strict";
4 |
5 | var partial = require("es5-ext/function/#/partial")
6 | , forEach = require("es5-ext/object/for-each")
7 | , pad = require("es5-ext/string/#/pad")
8 | , compact = require("es5-ext/array/#/compact")
9 | , d = require("d")
10 | , memoize = require("./plain");
11 |
12 | var max = Math.max, stats = (exports.statistics = {});
13 |
14 | Object.defineProperty(
15 | memoize, "__profiler__",
16 | d(function (conf) {
17 | var id, source, data, stack;
18 | stack = new Error().stack;
19 | if (
20 | !stack ||
21 | !stack
22 | .split("\n")
23 | .slice(3)
24 | .some(function (line) {
25 | if (line.indexOf("/memoizee/") === -1 && line.indexOf(" (native)") === -1) {
26 | source = line.replace(/\n/g, "\\n").trim();
27 | return true;
28 | }
29 | return false;
30 | })
31 | ) {
32 | source = "unknown";
33 | }
34 | id = compact.call([conf.profileName, source]).join(", ");
35 |
36 | if (!stats[id]) stats[id] = { initial: 0, cached: 0 };
37 | data = stats[id];
38 |
39 | conf.on("set", function () { ++data.initial; });
40 | conf.on("get", function () { ++data.cached; });
41 | })
42 | );
43 |
44 | exports.log = function () {
45 | var initial, cached, ordered, ipad, cpad, ppad, toPrc, log;
46 |
47 | initial = cached = 0;
48 | ordered = [];
49 |
50 | toPrc = function (initialCount, cachedCount) {
51 | if (!initialCount && !cachedCount) {
52 | return "0.00";
53 | }
54 | return ((cachedCount / (initialCount + cachedCount)) * 100).toFixed(2);
55 | };
56 |
57 | log = "------------------------------------------------------------\n";
58 | log += "Memoize statistics:\n\n";
59 |
60 | forEach(
61 | stats,
62 | function (data, name) {
63 | initial += data.initial;
64 | cached += data.cached;
65 | ordered.push([name, data]);
66 | },
67 | null,
68 | function (nameA, nameB) {
69 | return (
70 | this[nameB].initial +
71 | this[nameB].cached -
72 | (this[nameA].initial + this[nameA].cached)
73 | );
74 | }
75 | );
76 |
77 | ipad = partial.call(pad, " ", max(String(initial).length, "Init".length));
78 | cpad = partial.call(pad, " ", max(String(cached).length, "Cache".length));
79 | ppad = partial.call(pad, " ", "%Cache".length);
80 | log +=
81 | ipad.call("Init") +
82 | " " +
83 | cpad.call("Cache") +
84 | " " +
85 | ppad.call("%Cache") +
86 | " Source location\n";
87 | log +=
88 | ipad.call(initial) +
89 | " " +
90 | cpad.call(cached) +
91 | " " +
92 | ppad.call(toPrc(initial, cached)) +
93 | " (all)\n";
94 | ordered.forEach(function (data) {
95 | var name = data[0];
96 | data = data[1];
97 | log +=
98 | ipad.call(data.initial) +
99 | " " +
100 | cpad.call(data.cached) +
101 | " " +
102 | ppad.call(toPrc(data.initial, data.cached)) +
103 | " " +
104 | name +
105 | "\n";
106 | });
107 | log += "------------------------------------------------------------\n";
108 | return log;
109 | };
110 |
--------------------------------------------------------------------------------
/tea.yaml:
--------------------------------------------------------------------------------
1 | # https://tea.xyz/what-is-this-file
2 | ---
3 | version: 1.0.0
4 | codeOwners:
5 | - "0x641A74E8f6b1f59ffadc28b220A316c79a65D87e"
6 | quorum: 1
7 |
--------------------------------------------------------------------------------
/test/ext/async.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, func-names: 0, handle-callback-err: 0, max-lines: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..")
6 | , nextTick = require("next-tick");
7 |
8 | module.exports = function () {
9 | return {
10 | "Regular": {
11 | Success: function (a, d) {
12 | var mfn, fn, u = {}, i = 0, invoked = 0;
13 | fn = function (x, y, cb) {
14 | nextTick(function () {
15 | ++i;
16 | cb(null, x + y);
17 | });
18 | return u;
19 | };
20 |
21 | mfn = memoize(fn, { async: true });
22 |
23 | a(
24 | mfn(3, 7, function (err, res) {
25 | ++invoked;
26 | a.deep([err, res], [null, 10], "Result #1");
27 | }),
28 | u, "Initial"
29 | );
30 | a(
31 | mfn(3, 7, function (err, res) {
32 | ++invoked;
33 | a.deep([err, res], [null, 10], "Result #2");
34 | }),
35 | u, "Initial #2"
36 | );
37 | a(
38 | mfn(5, 8, function (err, res) {
39 | ++invoked;
40 | a.deep([err, res], [null, 13], "Result B #1");
41 | }),
42 | u, "Initial #2"
43 | );
44 | a(
45 | mfn(3, 7, function (err, res) {
46 | ++invoked;
47 | a.deep([err, res], [null, 10], "Result #3");
48 | }),
49 | u, "Initial #2"
50 | );
51 | a(
52 | mfn(5, 8, function (err, res) {
53 | ++invoked;
54 | a.deep([err, res], [null, 13], "Result B #2");
55 | }),
56 | u, "Initial #3"
57 | );
58 |
59 | nextTick(function () {
60 | a(i, 2, "Init Called");
61 | a(invoked, 5, "Cb Called");
62 |
63 | a(
64 | mfn(3, 7, function (err, res) {
65 | ++invoked;
66 | a.deep([err, res], [null, 10], "Again: Result");
67 | }),
68 | u, "Again: Initial"
69 | );
70 | a(
71 | mfn(5, 8, function (err, res) {
72 | ++invoked;
73 | a.deep([err, res], [null, 13], "Again B: Result");
74 | }),
75 | u, "Again B: Initial"
76 | );
77 |
78 | nextTick(function () {
79 | a(i, 2, "Init Called #2");
80 | a(invoked, 7, "Cb Called #2");
81 |
82 | mfn.delete(3, 7);
83 |
84 | a(
85 | mfn(3, 7, function (err, res) {
86 | ++invoked;
87 | a.deep([err, res], [null, 10], "Again: Result");
88 | }),
89 | u, "Again: Initial"
90 | );
91 | a(
92 | mfn(5, 8, function (err, res) {
93 | ++invoked;
94 | a.deep([err, res], [null, 13], "Again B: Result");
95 | }),
96 | u, "Again B: Initial"
97 | );
98 |
99 | nextTick(function () {
100 | a(i, 3, "Init After delete");
101 | a(invoked, 9, "Cb After delete");
102 | d();
103 | });
104 | });
105 | });
106 | },
107 | Error: function (a, d) {
108 | var mfn, fn, u = {}, i = 0, e = new Error("Test");
109 | fn = function (x, y, cb) {
110 | nextTick(function () {
111 | ++i;
112 | cb(e);
113 | });
114 | return u;
115 | };
116 |
117 | mfn = memoize(fn, { async: true, dispose: a.never });
118 |
119 | a(
120 | mfn(3, 7, function (err, res) {
121 | a.deep([err, res], [e, undefined], "Result #1");
122 | }),
123 | u, "Initial"
124 | );
125 | a(
126 | mfn(3, 7, function (err, res) {
127 | a.deep([err, res], [e, undefined], "Result #2");
128 | }),
129 | u, "Initial #2"
130 | );
131 | a(
132 | mfn(5, 8, function (err, res) {
133 | a.deep([err, res], [e, undefined], "Result B #1");
134 | }),
135 | u, "Initial #2"
136 | );
137 | a(
138 | mfn(3, 7, function (err, res) {
139 | a.deep([err, res], [e, undefined], "Result #3");
140 | }),
141 | u, "Initial #2"
142 | );
143 | a(
144 | mfn(5, 8, function (err, res) {
145 | a.deep([err, res], [e, undefined], "Result B #2");
146 | }),
147 | u, "Initial #3"
148 | );
149 |
150 | nextTick(function () {
151 | a(i, 2, "Called #2");
152 |
153 | a(
154 | mfn(3, 7, function (err, res) {
155 | a.deep([err, res], [e, undefined], "Again: Result");
156 | }),
157 | u, "Again: Initial"
158 | );
159 | a(
160 | mfn(5, 8, function (err, res) {
161 | a.deep([err, res], [e, undefined], "Again B: Result");
162 | }),
163 | u, "Again B: Initial"
164 | );
165 |
166 | nextTick(function () {
167 | a(i, 4, "Again Called #2");
168 | d();
169 | });
170 | });
171 | },
172 | },
173 | "Primitive": {
174 | "Success": function (a, d) {
175 | var mfn, fn, u = {}, i = 0;
176 | fn = function (x, y, cb) {
177 | nextTick(function () {
178 | ++i;
179 | cb(null, x + y);
180 | });
181 | return u;
182 | };
183 |
184 | mfn = memoize(fn, { async: true, primitive: true });
185 |
186 | a(
187 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #1"); }),
188 | u, "Initial"
189 | );
190 | a(
191 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #2"); }),
192 | u, "Initial #2"
193 | );
194 | a(
195 | mfn(5, 8, function (err, res) {
196 | a.deep([err, res], [null, 13], "Result B #1");
197 | }),
198 | u, "Initial #2"
199 | );
200 | a(
201 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #3"); }),
202 | u, "Initial #2"
203 | );
204 | a(
205 | mfn(5, 8, function (err, res) {
206 | a.deep([err, res], [null, 13], "Result B #2");
207 | }),
208 | u, "Initial #3"
209 | );
210 |
211 | nextTick(function () {
212 | a(i, 2, "Called #2");
213 |
214 | a(
215 | mfn(3, 7, function (err, res) {
216 | a.deep([err, res], [null, 10], "Again: Result");
217 | }),
218 | u, "Again: Initial"
219 | );
220 | a(
221 | mfn(5, 8, function (err, res) {
222 | a.deep([err, res], [null, 13], "Again B: Result");
223 | }),
224 | u, "Again B: Initial"
225 | );
226 |
227 | nextTick(function () {
228 | a(i, 2, "Again Called #2");
229 |
230 | mfn.delete(3, 7);
231 |
232 | a(
233 | mfn(3, 7, function (err, res) {
234 | a.deep([err, res], [null, 10], "Again: Result");
235 | }),
236 | u, "Again: Initial"
237 | );
238 | a(
239 | mfn(5, 8, function (err, res) {
240 | a.deep([err, res], [null, 13], "Again B: Result");
241 | }),
242 | u, "Again B: Initial"
243 | );
244 |
245 | nextTick(function () {
246 | a(i, 3, "Call After delete");
247 | d();
248 | });
249 | });
250 | });
251 | },
252 | "Error": function (a, d) {
253 | var mfn, fn, u = {}, i = 0, e = new Error("Test");
254 | fn = function (x, y, cb) {
255 | nextTick(function () {
256 | ++i;
257 | cb(e);
258 | });
259 | return u;
260 | };
261 |
262 | mfn = memoize(fn, { async: true, primitive: true });
263 |
264 | a(
265 | mfn(3, 7, function (err, res) {
266 | a.deep([err, res], [e, undefined], "Result #1");
267 | }),
268 | u, "Initial"
269 | );
270 | a(
271 | mfn(3, 7, function (err, res) {
272 | a.deep([err, res], [e, undefined], "Result #2");
273 | }),
274 | u, "Initial #2"
275 | );
276 | a(
277 | mfn(5, 8, function (err, res) {
278 | a.deep([err, res], [e, undefined], "Result B #1");
279 | }),
280 | u, "Initial #2"
281 | );
282 | a(
283 | mfn(3, 7, function (err, res) {
284 | a.deep([err, res], [e, undefined], "Result #3");
285 | }),
286 | u, "Initial #2"
287 | );
288 | a(
289 | mfn(5, 8, function (err, res) {
290 | a.deep([err, res], [e, undefined], "Result B #2");
291 | }),
292 | u, "Initial #3"
293 | );
294 |
295 | nextTick(function () {
296 | a(i, 2, "Called #2");
297 |
298 | a(
299 | mfn(3, 7, function (err, res) {
300 | a.deep([err, res], [e, undefined], "Again: Result");
301 | }),
302 | u, "Again: Initial"
303 | );
304 | a(
305 | mfn(5, 8, function (err, res) {
306 | a.deep([err, res], [e, undefined], "Again B: Result");
307 | }),
308 | u, "Again B: Initial"
309 | );
310 |
311 | nextTick(function () {
312 | a(i, 4, "Again Called #2");
313 | d();
314 | });
315 | });
316 | },
317 | "Primitive null arg case": function (a, d) {
318 | var x = {}
319 | , mfn = memoize(function f(id, cb) { cb(null, x); }, {
320 | async: true,
321 | primitive: true,
322 | });
323 |
324 | mfn(null, function (err, res) {
325 | a.deep([err, res], [null, x], "Args");
326 | d();
327 | });
328 | },
329 | },
330 | "Sync Clear": function (a, d) {
331 | var mfn, fn;
332 | fn = function (x, cb) {
333 | nextTick(function () { cb(null, x); });
334 | };
335 |
336 | mfn = memoize(fn, { async: true });
337 | mfn(1, function (err, i) { a(i, 1, "First"); });
338 | mfn.clear();
339 | mfn(2, function (err, i) {
340 | a(i, 2, "Second");
341 | d();
342 | });
343 | },
344 | "Sync Clear: Primitive": function (a, d) {
345 | var mfn, fn;
346 | fn = function (x, cb) {
347 | nextTick(function () { cb(null, x); });
348 | };
349 | mfn = memoize(fn, { async: true, primitive: true });
350 |
351 | mfn(2, function (err, i) { a(i, 2, "First"); });
352 | mfn(1, function (err, i) {
353 | a(i, 1, "Second");
354 | nextTick(d);
355 | });
356 | mfn.clear();
357 | mfn(2, function (err, i) { a(i, 2, "Third"); });
358 | },
359 | };
360 | };
361 |
--------------------------------------------------------------------------------
/test/ext/dispose.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, max-lines: 0, max-statements: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..")
6 | , nextTick = require("next-tick")
7 | , delay = require("timers-ext/delay")
8 | , Promise = require("plain-promise");
9 |
10 | module.exports = function () {
11 | return {
12 | Regular: {
13 | "Sync": function (a) {
14 | var mfn, fn, value = [], x, invoked;
15 | fn = function (arg1, arg2) { return arg1 + arg2; };
16 | mfn = memoize(fn, { dispose: function (val) { value.push(val); } });
17 | mfn(3, 7);
18 | mfn(5, 8);
19 | mfn(12, 4);
20 | a.deep(value, [], "Pre");
21 | mfn.delete(5, 8);
22 | a.deep(value, [13], "#1");
23 | value = [];
24 | mfn.delete(12, 4);
25 | a.deep(value, [16], "#2");
26 |
27 | value = [];
28 | mfn(77, 11);
29 | mfn.clear();
30 | a.deep(value, [10, 88], "Clear all");
31 |
32 | x = {};
33 | invoked = false;
34 | mfn = memoize(function () { return x; }, {
35 | dispose: function (val) { invoked = val; },
36 | });
37 |
38 | mfn.delete();
39 | a(invoked, false, "No args: Post invalid delete");
40 | mfn();
41 | a(invoked, false, "No args: Post cache");
42 | mfn.delete();
43 | a(invoked, x, "No args: Pre delete");
44 | },
45 | "Ref counter": function (a) {
46 | var mfn, fn, value = [];
47 | fn = function (x, y) { return x + y; };
48 | mfn = memoize(fn, {
49 | refCounter: true,
50 | dispose: function (val) { value.push(val); },
51 | });
52 |
53 | mfn(3, 7);
54 | mfn(5, 8);
55 | mfn(12, 4);
56 | a.deep(value, [], "Pre");
57 | mfn(5, 8);
58 | mfn.deleteRef(5, 8);
59 | a.deep(value, [], "Pre");
60 | mfn.deleteRef(5, 8);
61 | a.deep(value, [13], "#1");
62 | value = [];
63 | mfn.deleteRef(12, 4);
64 | a.deep(value, [16], "#2");
65 |
66 | value = [];
67 | mfn(77, 11);
68 | mfn.clear();
69 | a.deep(value, [10, 88], "Clear all");
70 | },
71 | "Async": function (a, d) {
72 | var mfn, fn, u = {}, value = [];
73 | fn = function (x, y, cb) {
74 | nextTick(function () { cb(null, x + y); });
75 | return u;
76 | };
77 |
78 | mfn = memoize(fn, { async: true, dispose: function (val) { value.push(val); } });
79 |
80 | mfn(3, 7, function () {
81 | mfn(5, 8, function () {
82 | mfn(12, 4, function () {
83 | a.deep(value, [], "Pre");
84 | mfn.delete(5, 8);
85 | a.deep(value, [13], "#1");
86 | value = [];
87 | mfn.delete(12, 4);
88 | a.deep(value, [16], "#2");
89 |
90 | value = [];
91 | mfn(77, 11, function () {
92 | mfn.clear();
93 | a.deep(value, [10, 88], "Clear all");
94 | d();
95 | });
96 | });
97 | });
98 | });
99 | },
100 | "Promise": function (a, d) {
101 | var mfn, fn, value = [];
102 | fn = function (x, y) {
103 | return new Promise(function (res) { res(x + y); });
104 | };
105 |
106 | mfn = memoize(fn, { promise: true, dispose: function (val) { value.push(val); } });
107 |
108 | mfn(3, 7).done(function () {
109 | mfn(5, 8).done(function () {
110 | mfn(12, 4).done(
111 | delay(function () {
112 | a.deep(value, [], "Pre");
113 | mfn.delete(5, 8);
114 | a.deep(value, [13], "#1");
115 | value = [];
116 | mfn.delete(12, 4);
117 | a.deep(value, [16], "#2");
118 |
119 | value = [];
120 | mfn(77, 11).done(
121 | delay(function () {
122 | mfn.clear();
123 | a.deep(value, [10, 88], "Clear all");
124 | d();
125 | })
126 | );
127 | })
128 | );
129 | });
130 | });
131 | },
132 | },
133 | Primitive: {
134 | "Sync": function (a) {
135 | var mfn, fn, value = [];
136 | fn = function (x, y) { return x + y; };
137 | mfn = memoize(fn, { dispose: function (val) { value.push(val); } });
138 |
139 | mfn(3, 7);
140 | mfn(5, 8);
141 | mfn(12, 4);
142 | a.deep(value, [], "Pre");
143 | mfn.delete(5, 8);
144 | a.deep(value, [13], "#1");
145 | value = [];
146 | mfn.delete(12, 4);
147 | a.deep(value, [16], "#2");
148 |
149 | value = [];
150 | mfn(77, 11);
151 | mfn.clear();
152 | a.deep(value, [10, 88], "Clear all");
153 | },
154 | "Ref counter": function (a) {
155 | var mfn, fn, value = [];
156 | fn = function (x, y) { return x + y; };
157 | mfn = memoize(fn, {
158 | refCounter: true,
159 | dispose: function (val) { value.push(val); },
160 | });
161 |
162 | mfn(3, 7);
163 | mfn(5, 8);
164 | mfn(12, 4);
165 | a.deep(value, [], "Pre");
166 | mfn(5, 8);
167 | mfn.deleteRef(5, 8);
168 | a.deep(value, [], "Pre");
169 | mfn.deleteRef(5, 8);
170 | a.deep(value, [13], "#1");
171 | value = [];
172 | mfn.deleteRef(12, 4);
173 | a.deep(value, [16], "#2");
174 |
175 | value = [];
176 | mfn(77, 11);
177 | mfn.clear();
178 | a.deep(value, [10, 88], "Clear all");
179 | },
180 | "Async": function (a, d) {
181 | var mfn, fn, u = {}, value = [];
182 | fn = function (x, y, cb) {
183 | nextTick(function () { cb(null, x + y); });
184 | return u;
185 | };
186 |
187 | mfn = memoize(fn, { async: true, dispose: function (val) { value.push(val); } });
188 |
189 | mfn(3, 7, function () {
190 | mfn(5, 8, function () {
191 | mfn(12, 4, function () {
192 | a.deep(value, [], "Pre");
193 | mfn.delete(5, 8);
194 | a.deep(value, [13], "#1");
195 | value = [];
196 | mfn.delete(12, 4);
197 | a.deep(value, [16], "#2");
198 |
199 | value = [];
200 | mfn(77, 11, function () {
201 | mfn.clear();
202 | a.deep(value, [10, 88], "Clear all");
203 | d();
204 | });
205 | });
206 | });
207 | });
208 | },
209 | "Promise": function (a, d) {
210 | var mfn, fn, value = [];
211 | fn = function (x, y) {
212 | return new Promise(function (res) { res(x + y); });
213 | };
214 |
215 | mfn = memoize(fn, { promise: true, dispose: function (val) { value.push(val); } });
216 |
217 | mfn(3, 7).done(function () {
218 | mfn(5, 8).done(function () {
219 | mfn(12, 4).done(
220 | delay(function () {
221 | a.deep(value, [], "Pre");
222 | mfn.delete(5, 8);
223 | a.deep(value, [13], "#1");
224 | value = [];
225 | mfn.delete(12, 4);
226 | a.deep(value, [16], "#2");
227 |
228 | value = [];
229 | mfn(77, 11).done(
230 | delay(function () {
231 | mfn.clear();
232 | a.deep(value, [10, 88], "Clear all");
233 | d();
234 | })
235 | );
236 | })
237 | );
238 | });
239 | });
240 | },
241 | },
242 | };
243 | };
244 |
--------------------------------------------------------------------------------
/test/ext/max-age.js:
--------------------------------------------------------------------------------
1 | /* eslint max-lines: 0, id-length: 0, func-names: 0, handle-callback-err: 0, max-lines: 0,
2 | no-unused-vars: 0, max-nested-callbacks: 0, no-shadow: 0, max-len: 0 */
3 |
4 | "use strict";
5 |
6 | var memoize = require("../..")
7 | , nextTick = require("next-tick")
8 | , delay = require("timers-ext/delay")
9 | , Promise = require("plain-promise");
10 |
11 | require("../../ext/async");
12 | require("../../ext/promise");
13 |
14 | module.exports = function () {
15 | return {
16 | Regular: {
17 | Sync: function (a, d) {
18 | var mfn, fn, i = 0;
19 | fn = function (x, y) {
20 | ++i;
21 | return x + y;
22 | };
23 | mfn = memoize(fn, { maxAge: 100 });
24 |
25 | a(mfn(3, 7), 10, "Result #1");
26 | a(i, 1, "Called #1");
27 | a(mfn(3, 7), 10, "Result #2");
28 | a(i, 1, "Called #2");
29 | a(mfn(5, 8), 13, "Result B #1");
30 | a(i, 2, "Called B #1");
31 | a(mfn(3, 7), 10, "Result #3");
32 | a(i, 2, "Called #3");
33 | a(mfn(5, 8), 13, "Result B #2");
34 | a(i, 2, "Called B #2");
35 |
36 | setTimeout(function () {
37 | a(mfn(3, 7), 10, "Result: Wait");
38 | a(i, 2, "Called: Wait");
39 | a(mfn(5, 8), 13, "Result: Wait B");
40 | a(i, 2, "Called: Wait B");
41 |
42 | a(mfn(9, 1), 10, "Result: C");
43 | a(i, 3, "Called: C");
44 | setTimeout(function () {
45 | a(mfn(3, 7), 10, "Result: Wait After");
46 | a(i, 4, "Called: Wait After");
47 | a(mfn(5, 8), 13, "Result: Wait After B");
48 | a(i, 5, "Called: Wait After B");
49 |
50 | a(mfn(3, 7), 10, "Result: Wait After #2");
51 | a(i, 5, "Called: Wait After #2");
52 | a(mfn(5, 8), 13, "Result: Wait After B #2");
53 | a(i, 5, "Called: Wait After B #2");
54 |
55 | a(mfn(9, 1), 10, "Result: WiatC");
56 | a(i, 5, "Called: Wait C");
57 | d();
58 | }, 70);
59 | }, 40);
60 | },
61 | Promise: function (a, d) {
62 | var mfn, fn, i = 0;
63 | fn = function (x, y) {
64 | return new Promise(function (res) {
65 | ++i;
66 | res(x + y);
67 | });
68 | };
69 |
70 | mfn = memoize(fn, { promise: true, maxAge: 100 });
71 |
72 | mfn(3, 7).done(function (res) { a(res, 10, "Result #1"); });
73 | mfn(5, 8).done(function (res) { a(res, 13, "Result #2"); });
74 | mfn(3, 7).done(function (res) { a(res, 10, "Result #3"); });
75 | mfn(3, 7).done(function (res) { a(res, 10, "Result #4"); });
76 | mfn(5, 8).done(function (res) { a(res, 13, "Result #5"); });
77 |
78 | setTimeout(function () {
79 | a(i, 2, "Called #2");
80 |
81 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result #1"); });
82 | mfn(5, 8).done(function (res) { a(res, 13, "Again: Result #2"); });
83 |
84 | setTimeout(function () {
85 | a(i, 2, "Again Called #2");
86 |
87 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result #1"); });
88 | mfn(5, 8).done(function (res) { a(res, 13, "Again: Result #2"); });
89 |
90 | nextTick(function () {
91 | a(i, 4, "Call After clear");
92 | d();
93 | });
94 | }, 100);
95 | }, 20);
96 | },
97 | Async: function (a, d) {
98 | var mfn, fn, u = {}, i = 0;
99 | fn = function (x, y, cb) {
100 | nextTick(function () {
101 | ++i;
102 | cb(null, x + y);
103 | });
104 | return u;
105 | };
106 |
107 | mfn = memoize(fn, { async: true, maxAge: 100 });
108 |
109 | a(
110 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #1"); }),
111 | u, "Initial"
112 | );
113 | a(
114 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #2"); }),
115 | u, "Initial #2"
116 | );
117 | a(
118 | mfn(5, 8, function (err, res) {
119 | a.deep([err, res], [null, 13], "Result B #1");
120 | }),
121 | u, "Initial #2"
122 | );
123 | a(
124 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #3"); }),
125 | u, "Initial #2"
126 | );
127 | a(
128 | mfn(5, 8, function (err, res) {
129 | a.deep([err, res], [null, 13], "Result B #2");
130 | }),
131 | u, "Initial #3"
132 | );
133 |
134 | setTimeout(function () {
135 | a(i, 2, "Called #2");
136 |
137 | a(
138 | mfn(3, 7, function (err, res) {
139 | a.deep([err, res], [null, 10], "Again: Result");
140 | }),
141 | u, "Again: Initial"
142 | );
143 | a(
144 | mfn(5, 8, function (err, res) {
145 | a.deep([err, res], [null, 13], "Again B: Result");
146 | }),
147 | u, "Again B: Initial"
148 | );
149 |
150 | setTimeout(function () {
151 | a(i, 2, "Again Called #2");
152 |
153 | a(
154 | mfn(3, 7, function (err, res) {
155 | a.deep([err, res], [null, 10], "Again: Result");
156 | }),
157 | u, "Again: Initial"
158 | );
159 | a(
160 | mfn(5, 8, function (err, res) {
161 | a.deep([err, res], [null, 13], "Again B: Result");
162 | }),
163 | u, "Again B: Initial"
164 | );
165 |
166 | nextTick(function () {
167 | a(i, 4, "Call After clear");
168 | d();
169 | });
170 | }, 100);
171 | }, 20);
172 | },
173 | },
174 | Primitive: {
175 | Sync: function (a, d) {
176 | var mfn, fn, i = 0;
177 | fn = function (x, y) {
178 | ++i;
179 | return x + y;
180 | };
181 | mfn = memoize(fn, { primitive: true, maxAge: 100 });
182 |
183 | a(mfn(3, 7), 10, "Result #1");
184 | a(i, 1, "Called #1");
185 | a(mfn(3, 7), 10, "Result #2");
186 | a(i, 1, "Called #2");
187 | a(mfn(5, 8), 13, "Result B #1");
188 | a(i, 2, "Called B #1");
189 | a(mfn(3, 7), 10, "Result #3");
190 | a(i, 2, "Called #3");
191 | a(mfn(5, 8), 13, "Result B #2");
192 | a(i, 2, "Called B #2");
193 |
194 | setTimeout(function () {
195 | a(mfn(3, 7), 10, "Result: Wait");
196 | a(i, 2, "Called: Wait");
197 | a(mfn(5, 8), 13, "Result: Wait B");
198 | a(i, 2, "Called: Wait B");
199 |
200 | setTimeout(function () {
201 | a(mfn(3, 7), 10, "Result: Wait After");
202 | a(i, 3, "Called: Wait After");
203 | a(mfn(5, 8), 13, "Result: Wait After B");
204 | a(i, 4, "Called: Wait After B");
205 |
206 | a(mfn(3, 7), 10, "Result: Wait After #2");
207 | a(i, 4, "Called: Wait After #2");
208 | a(mfn(5, 8), 13, "Result: Wait After B #2");
209 | a(i, 4, "Called: Wait After B #2");
210 | d();
211 | }, 100);
212 | }, 20);
213 | },
214 | Async: function (a, d) {
215 | var mfn, fn, u = {}, i = 0;
216 | fn = function (x, y, cb) {
217 | nextTick(function () {
218 | ++i;
219 | cb(null, x + y);
220 | });
221 | return u;
222 | };
223 |
224 | mfn = memoize(fn, { async: true, primitive: true, maxAge: 100 });
225 |
226 | a(
227 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #1"); }),
228 | u, "Initial"
229 | );
230 | a(
231 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #2"); }),
232 | u, "Initial #2"
233 | );
234 | a(
235 | mfn(5, 8, function (err, res) {
236 | a.deep([err, res], [null, 13], "Result B #1");
237 | }),
238 | u, "Initial #2"
239 | );
240 | a(
241 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #3"); }),
242 | u, "Initial #2"
243 | );
244 | a(
245 | mfn(5, 8, function (err, res) {
246 | a.deep([err, res], [null, 13], "Result B #2");
247 | }),
248 | u, "Initial #3"
249 | );
250 |
251 | setTimeout(function () {
252 | a(i, 2, "Called #2");
253 |
254 | a(
255 | mfn(3, 7, function (err, res) {
256 | a.deep([err, res], [null, 10], "Again: Result");
257 | }),
258 | u, "Again: Initial"
259 | );
260 | a(
261 | mfn(5, 8, function (err, res) {
262 | a.deep([err, res], [null, 13], "Again B: Result");
263 | }),
264 | u, "Again B: Initial"
265 | );
266 |
267 | setTimeout(function () {
268 | a(i, 2, "Again Called #2");
269 |
270 | a(
271 | mfn(3, 7, function (err, res) {
272 | a.deep([err, res], [null, 10], "Again: Result");
273 | }),
274 | u, "Again: Initial"
275 | );
276 | a(
277 | mfn(5, 8, function (err, res) {
278 | a.deep([err, res], [null, 13], "Again B: Result");
279 | }),
280 | u, "Again B: Initial"
281 | );
282 |
283 | nextTick(function () {
284 | a(i, 4, "Call After clear");
285 | d();
286 | });
287 | }, 100);
288 | }, 20);
289 | },
290 | Promise: function (a, d) {
291 | var mfn, fn, i = 0;
292 | fn = function (x, y, cb) {
293 | return new Promise(function (res) {
294 | ++i;
295 | res(x + y);
296 | });
297 | };
298 |
299 | mfn = memoize(fn, { promise: true, primitive: true, maxAge: 500 });
300 |
301 | mfn(3, 7).done(function (res) { a.deep(res, 10, "Result #1"); });
302 | mfn(3, 7).done(function (res) { a.deep(res, 10, "Result #2"); });
303 | mfn(5, 8).done(function (res) { a.deep(res, 13, "Result B #1"); });
304 | mfn(3, 7).done(function (res) { a.deep(res, 10, "Result #3"); });
305 | mfn(5, 8).done(function (res) { a.deep(res, 13, "Result B #2"); });
306 |
307 | // 20
308 | setTimeout(function () {
309 | a(i, 2, "Called #2");
310 |
311 | mfn(3, 7).done(function (res) { a.deep(res, 10, "Again: Result"); });
312 | mfn(5, 8).done(function (res) { a.deep(res, 13, "Again B: Result"); });
313 |
314 | // 100
315 | setTimeout(function () {
316 | a(i, 2, "Again Called #2");
317 |
318 | mfn(3, 7).done(function (res) { a.deep(res, 10, "Again: Result"); });
319 | mfn(5, 8).done(function (res) { a.deep(res, 13, "Again B: Result"); });
320 |
321 | nextTick(function () {
322 | a(i, 4, "Call After clear");
323 | d();
324 | });
325 | }, 500);
326 | }, 100);
327 | },
328 | },
329 | Refetch: {
330 | Default: function (a, d) {
331 | var mfn, fn, i = 0;
332 | fn = function (x, y) {
333 | ++i;
334 | return x + y;
335 | };
336 | mfn = memoize(fn, { maxAge: 600, preFetch: true });
337 |
338 | a(mfn(3, 7), 10, "Result #1");
339 | a(i, 1, "Called #1");
340 | a(mfn(3, 7), 10, "Result #2");
341 | a(i, 1, "Called #2");
342 | a(mfn(5, 8), 13, "Result B #1");
343 | a(i, 2, "Called B #1");
344 | a(mfn(3, 7), 10, "Result #3");
345 | a(i, 2, "Called #3");
346 | a(mfn(5, 8), 13, "Result B #2");
347 | a(i, 2, "Called B #2");
348 |
349 | setTimeout(function () {
350 | a(mfn(3, 7), 10, "Result: Wait");
351 | a(i, 2, "Called: Wait");
352 | a(mfn(5, 8), 13, "Result: Wait B");
353 | a(i, 2, "Called: Wait B");
354 |
355 | setTimeout(function () {
356 | a(mfn(3, 7), 10, "Result: Wait After");
357 | a(i, 2, "Called: Wait After");
358 | a(mfn(5, 8), 13, "Result: Wait After B");
359 | a(i, 2, "Called: Wait After B");
360 |
361 | a(mfn(3, 7), 10, "Result: Wait After #2");
362 | a(i, 2, "Called: Wait After #2");
363 | a(mfn(5, 8), 13, "Result: Wait After B #2");
364 | a(i, 2, "Called: Wait After B #2");
365 |
366 | setTimeout(function () {
367 | a(i, 4, "Called: After Refetch: Before");
368 | a(mfn(3, 7), 10, "Result: After Refetch");
369 | a(i, 4, "Called: After Refetch: After");
370 | a(mfn(5, 8), 13, "Result: After Refetch B");
371 | a(i, 4, "Called: After Refetch B: After");
372 |
373 | setTimeout(function () {
374 | a(mfn(3, 7), 10, "Result: After Refetch #2");
375 | a(i, 4, "Called: After Refetch #2");
376 | a(mfn(5, 8), 13, "Result: After Refetch #2 B");
377 | a(i, 4, "Called: After Refetch #2 B");
378 |
379 | a(mfn(3, 7), 10, "Result: After Refetch #3");
380 | a(i, 4, "Called: After Refetch #3");
381 | a(mfn(5, 8), 13, "Result: After Refetch #3 B");
382 | a(i, 4, "Called: After Refetch #3 B");
383 | d();
384 | }, 200);
385 | }, 200);
386 | }, 200);
387 | }, 300);
388 | },
389 | Async: function (a, d) {
390 | var mfn, fn, i = 0;
391 | fn = function (x, y, cb) {
392 | ++i;
393 | setTimeout(function () { cb(null, x + y); }, 0);
394 | };
395 | mfn = memoize(fn, { maxAge: 600, preFetch: true, async: true });
396 |
397 | // 1.Start
398 | mfn(3, 7, function (err, result) {
399 | a(result, 10, "Result #1");
400 | a(i, 1, "Called #1");
401 | mfn(3, 7, function (err, result) {
402 | a(result, 10, "Result #2");
403 | a(i, 1, "Called #2");
404 | mfn(5, 8, function (err, result) {
405 | a(result, 13, "Result B #1");
406 | a(i, 2, "Called B #1");
407 | mfn(3, 7, function (err, result) {
408 | a(result, 10, "Result #3");
409 | a(i, 2, "Called #3");
410 | mfn(5, 8, function (err, result) {
411 | a(result, 13, "Result B #2");
412 | a(i, 2, "Called B #2");
413 | // 2. Wait 300ms
414 | setTimeout(function () {
415 | // From cache, prefetch not triggered
416 | mfn(3, 7, function (err, result) {
417 | a(result, 10, "Result: Wait");
418 | a(i, 2, "Called: Wait");
419 | mfn(5, 8, function (err, result) {
420 | a(result, 13, "Result: Wait B");
421 | a(i, 2, "Called: Wait B");
422 | // Wait 200ms
423 | setTimeout(function () {
424 | // From cache, prefetch triggered
425 | mfn(3, 7, function (err, result) {
426 | a(result, 10, "Result: Wait After");
427 | a(i, 2, "Called: Wait After");
428 | mfn(5, 8, function (err, result) {
429 | a(result, 13, "Result: Wait After B");
430 | a(i, 3, "Called: Wait After B");
431 | mfn(3, 7, function (err, result) {
432 | a(
433 | result, 10,
434 | "Result: Wait After #2"
435 | );
436 | a(i, 4, "Called: Wait After #2");
437 | mfn(5, 8, function (err, result) {
438 | a(
439 | result, 13,
440 | "Result: Wait After B #2"
441 | );
442 | a(
443 | i, 4,
444 | "Called: Wait After B #2"
445 | );
446 | // Wait 200ms
447 | setTimeout(function () {
448 | // From cache, prefetch not triggered
449 | a(
450 | i, 4,
451 | "Called: After Refetch: Before"
452 | );
453 | mfn(
454 | 3,
455 | 7,
456 | function (err, result) {
457 | a(
458 | result, 10,
459 | "Result: After Refetch"
460 | );
461 | a(
462 | i, 4,
463 | "Called: After Refetch: After"
464 | );
465 | mfn(
466 | 5,
467 | 8,
468 | function (
469 | err,
470 | result
471 | ) {
472 | a(
473 | result,
474 | 13,
475 | "Result: After Refetch B"
476 | );
477 | a(
478 | i, 4,
479 | "Called: After Refetch B: After"
480 | );
481 | // Wait 250ms
482 | setTimeout(
483 | function () {
484 | // From cache, prefetch triggered
485 | mfn(
486 | 3,
487 | 7,
488 | function (
489 | err,
490 | result
491 | ) {
492 | a(
493 | result,
494 | 10,
495 | "Result: After Refetch #2"
496 | );
497 | a(
498 | i,
499 | 4,
500 | "Called: After Refetch #2"
501 | );
502 | mfn(
503 | 5,
504 | 8,
505 | function (
506 | err,
507 | result
508 | ) {
509 | a(
510 | result,
511 | 13,
512 | "Result: After Refetch #2 B"
513 | );
514 | a(
515 | i,
516 | 5,
517 | "Called: After Refetch #2 B"
518 | );
519 | mfn(
520 | 3,
521 | 7,
522 | function (
523 | err,
524 | result
525 | ) {
526 | a(
527 | result,
528 | 10,
529 | "Result: After Refetch #3"
530 | );
531 | a(
532 | i,
533 | 6,
534 | "Called: After Refetch #3"
535 | );
536 | mfn(
537 | 5,
538 | 8,
539 | function (
540 | err,
541 | result
542 | ) {
543 | a(
544 | result,
545 | 13,
546 | "Result: After Refetch #3 B"
547 | );
548 | a(
549 | i,
550 | 6,
551 | "Called: After Refetch #3 B"
552 | );
553 | d();
554 | }
555 | );
556 | }
557 | );
558 | }
559 | );
560 | }
561 | );
562 | },
563 | 250
564 | );
565 | }
566 | );
567 | }
568 | );
569 | }, 200);
570 | });
571 | });
572 | });
573 | });
574 | }, 200);
575 | });
576 | });
577 | }, 300);
578 | });
579 | });
580 | });
581 | });
582 | });
583 | },
584 | Promise: function (a, d) {
585 | var mfn, fn, i = 0;
586 | fn = function (x, y) {
587 | ++i;
588 | return new Promise(function (res) { res(x + y); });
589 | };
590 | mfn = memoize(fn, { maxAge: 1200, preFetch: true, promise: true });
591 |
592 | mfn(3, 7).done(function (result) {
593 | a(result, 10, "Result #1");
594 | a(i, 1, "Called #1");
595 | mfn(3, 7).done(function (result) {
596 | a(result, 10, "Result #2");
597 | a(i, 1, "Called #2");
598 | mfn(5, 8).done(function (result) {
599 | a(result, 13, "Result B #1");
600 | a(i, 2, "Called B #1");
601 | mfn(3, 7).done(function (result) {
602 | a(result, 10, "Result #3");
603 | a(i, 2, "Called #3");
604 | mfn(5, 8).done(function (result) {
605 | a(result, 13, "Result B #2");
606 | a(i, 2, "Called B #2");
607 | // 600
608 | setTimeout(function () {
609 | mfn(3, 7).done(function (result) {
610 | a(result, 10, "Result: Wait");
611 | a(i, 2, "Called: Wait");
612 | mfn(5, 8).done(function (result) {
613 | a(result, 13, "Result: Wait B");
614 | a(i, 2, "Called: Wait B");
615 | // 400
616 | setTimeout(function () {
617 | mfn(3, 7).done(
618 | // 0
619 | delay(function (result) {
620 | a(result, 10, "Result: Wait After");
621 | a(i, 3, "Called: Wait After");
622 | mfn(5, 8).done(
623 | // 0
624 | delay(function (result) {
625 | a(
626 | result, 13,
627 | "Result: Wait After B"
628 | );
629 | a(i, 4, "Called: Wait After B");
630 | mfn(3, 7).done(
631 | // next tick
632 | delay(function (result) {
633 | a(
634 | result, 10,
635 | "Result: Wait After #2"
636 | );
637 | a(
638 | i, 4,
639 | "Called: Wait After #2"
640 | );
641 | mfn(5, 8).done(
642 | function (result) {
643 | a(
644 | result, 13,
645 | "Result: Wait After B #2"
646 | );
647 | a(
648 | i, 4,
649 | "Called: Wait After B #2"
650 | );
651 | // 400
652 | setTimeout(
653 | function () {
654 | a(
655 | i,
656 | 4,
657 | "Called: After Refetch: Before"
658 | );
659 | mfn(
660 | 3, 7
661 | ).done(
662 | function (
663 | result
664 | ) {
665 | a(
666 | result,
667 | 10,
668 | "Result: After Refetch"
669 | );
670 | a(
671 | i,
672 | 4,
673 | "Called: After Refetch: After"
674 | );
675 | mfn(
676 | 5,
677 | 8
678 | ).done(
679 | function (
680 | result
681 | ) {
682 | a(
683 | result,
684 | 13,
685 | "Result: After Refetch B"
686 | );
687 | a(
688 | i,
689 | 4,
690 | "Called: After Refetch B: After"
691 | );
692 | // 400
693 | setTimeout(
694 | function () {
695 | mfn(
696 | 3,
697 | 7
698 | ).done(
699 | // 0
700 | delay(
701 | function (
702 | result
703 | ) {
704 | a(
705 | result,
706 | 10,
707 | "Result: After Refetch #2"
708 | );
709 | a(
710 | i,
711 | 5,
712 | "Called: After Refetch #2"
713 | );
714 | mfn(
715 | 5,
716 | 8
717 | ).done(
718 | // 0
719 | delay(
720 | function (
721 | result
722 | ) {
723 | a(
724 | result,
725 | 13,
726 | "Result: After Refetch #2 B"
727 | );
728 | a(
729 | i,
730 | 6,
731 | "Called: After Refetch #2 B"
732 | );
733 | mfn(
734 | 3,
735 | 7
736 | ).done(
737 | function (
738 | result
739 | ) {
740 | a(
741 | result,
742 | 10,
743 | "Result: After Refetch #3"
744 | );
745 | a(
746 | i,
747 | 6,
748 | "Called: After Refetch #3"
749 | );
750 | mfn(
751 | 5,
752 | 8
753 | ).done(
754 | function (
755 | result
756 | ) {
757 | a(
758 | result,
759 | 13,
760 | "Result: After Refetch #3 B"
761 | );
762 | a(
763 | i,
764 | 6,
765 | "Called: After Refetch #3 B"
766 | );
767 | d();
768 | }
769 | );
770 | }
771 | );
772 | },
773 | 0
774 | )
775 | );
776 | },
777 | 0
778 | )
779 | );
780 | },
781 | 400
782 | );
783 | }
784 | );
785 | }
786 | );
787 | },
788 | 400
789 | );
790 | }
791 | );
792 | })
793 | );
794 | }, 0)
795 | );
796 | }, 0)
797 | );
798 | }, 400);
799 | });
800 | });
801 | }, 600);
802 | });
803 | });
804 | });
805 | });
806 | });
807 | },
808 | Custom: function (a, d) {
809 | var mfn, fn, i = 0;
810 | fn = function (x, y) {
811 | ++i;
812 | return x + y;
813 | };
814 | mfn = memoize(fn, { maxAge: 6000, preFetch: 1 / 6 });
815 | a(mfn(3, 7), 10, "Result #1");
816 | a(i, 1, "Called #1");
817 | a(mfn(3, 7), 10, "Result #2");
818 | a(i, 1, "Called #2");
819 | a(mfn(5, 8), 13, "Result B #1");
820 | a(i, 2, "Called B #1");
821 | a(mfn(3, 7), 10, "Result #3");
822 | a(i, 2, "Called #3");
823 | a(mfn(5, 8), 13, "Result B #2");
824 | a(i, 2, "Called B #2");
825 |
826 | setTimeout(function () {
827 | a(mfn(3, 7), 10, "Result: Wait");
828 | a(i, 2, "Called: Wait");
829 | a(mfn(5, 8), 13, "Result: Wait B");
830 | a(i, 2, "Called: Wait B");
831 |
832 | setTimeout(function () {
833 | a(mfn(3, 7), 10, "Result: Wait After");
834 | a(i, 2, "Called: Wait After");
835 | a(mfn(5, 8), 13, "Result: Wait After B");
836 | a(i, 2, "Called: Wait After B");
837 |
838 | a(mfn(3, 7), 10, "Result: Wait After #2");
839 | a(i, 2, "Called: Wait After #2");
840 | a(mfn(5, 8), 13, "Result: Wait After B #2");
841 | a(i, 2, "Called: Wait After B #2");
842 |
843 | setTimeout(function () {
844 | a(i, 4, "Called: After Refetch: Before");
845 | a(mfn(3, 7), 10, "Result: After Refetch");
846 | a(i, 4, "Called: After Refetch: After");
847 | a(mfn(5, 8), 13, "Result: After Refetch B");
848 | a(i, 4, "Called: After Refetch B: After");
849 |
850 | setTimeout(function () {
851 | a(mfn(3, 7), 10, "Result: After Refetch #2");
852 | a(i, 4, "Called: After Refetch #2");
853 | a(mfn(5, 8), 13, "Result: After Refetch #2 B");
854 | a(i, 4, "Called: After Refetch #2 B");
855 |
856 | a(mfn(3, 7), 10, "Result: After Refetch #3");
857 | a(i, 4, "Called: After Refetch #3");
858 | a(mfn(5, 8), 13, "Result: After Refetch #3 B");
859 | a(i, 4, "Called: After Refetch #3 B");
860 | d();
861 | }, 2000);
862 | }, 3000);
863 | }, 1000);
864 | }, 4500);
865 | },
866 | },
867 | };
868 | };
869 |
--------------------------------------------------------------------------------
/test/ext/promise.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, handle-callback-err: 0, no-undef: 0, no-unused-vars: 0, func-names: 0,
2 | max-lines: 0 */
3 |
4 | "use strict";
5 |
6 | var memoize = require("../..")
7 | , nextTick = require("next-tick")
8 | , Promise = require("plain-promise")
9 | , Bluebird = require("bluebird");
10 |
11 | Bluebird.config({ cancellation: true });
12 |
13 | module.exports = function () {
14 | return {
15 | "Regular": {
16 | Success: function (a, d) {
17 | var mfn, fn, i = 0, invoked = 0;
18 | fn = function (x, y) {
19 | return new Promise(function (res) {
20 | ++i;
21 | res(x + y);
22 | });
23 | };
24 |
25 | mfn = memoize(fn, { promise: true });
26 |
27 | mfn(3, 7).done(function (res) {
28 | ++invoked;
29 | a(res, 10, "Result #1");
30 | }, a.never);
31 |
32 | mfn(3, 7).done(function (res) {
33 | ++invoked;
34 | a(res, 10, "Result #2");
35 | }, a.never);
36 |
37 | mfn(5, 8).done(function (res) {
38 | ++invoked;
39 | a(res, 13, "Result B #1");
40 | }, a.never);
41 |
42 | mfn(3, 7).done(function (res) {
43 | ++invoked;
44 | a(res, 10, "Result #3");
45 | }, a.never);
46 |
47 | mfn(5, 8).done(function (res) {
48 | ++invoked;
49 | a(res, 13, "Result B #2");
50 | }, a.never);
51 |
52 | setTimeout(function () {
53 | a(i, 2, "Init Called");
54 | a(invoked, 5, "Cb Called");
55 |
56 | mfn(3, 7).done(function (res) {
57 | ++invoked;
58 | a(res, 10, "Again: Result");
59 | }, a.never);
60 |
61 | mfn(5, 8).done(function (res) {
62 | ++invoked;
63 | a(res, 13, "Again B: Result");
64 | }, a.never);
65 |
66 | setTimeout(function () {
67 | a(i, 2, "Init Called #2");
68 | a(invoked, 7, "Cb Called #2");
69 |
70 | mfn.delete(3, 7);
71 |
72 | mfn(3, 7).done(function (res) {
73 | ++invoked;
74 | a(res, 10, "Again: Result");
75 | }, a.never);
76 |
77 | mfn(5, 8).done(function (res) {
78 | ++invoked;
79 | a(res, 13, "Again B: Result");
80 | }, a.never);
81 |
82 | setTimeout(function () {
83 | a(i, 3, "Init After delete");
84 | a(invoked, 9, "Cb After delete");
85 | d();
86 | }, 100);
87 | }, 100);
88 | }, 100);
89 | },
90 | Error: function (a, d) {
91 | var mfn, fn, i = 0, e = new Error("Test");
92 | fn = function (x, y) {
93 | ++i;
94 | return new Promise(function (res, rej) { rej(e); });
95 | };
96 |
97 | mfn = memoize(fn, { promise: "done", dispose: a.never });
98 |
99 | mfn(3, 7).done(a.never, function (err) { a(err, e, "Result #1"); });
100 |
101 | mfn(5, 8).done(a.never, function (err) { a(err, e, "Result B #2"); });
102 |
103 | setTimeout(function () {
104 | a(i, 2, "Called #2");
105 |
106 | mfn(3, 7).done(a.never, function (err) { a(err, e, "Again: Result"); });
107 |
108 | mfn(5, 8).done(a.never, function (err) { a(err, e, "Again B: Result"); });
109 |
110 | setTimeout(function (err) {
111 | a(i, 4, "Again Called #2");
112 | d();
113 | }, 10);
114 | }, 10);
115 | },
116 | },
117 | "Cancellation": {
118 | Immediate: function (a, d) {
119 | var mfn, fn, i = 0;
120 | fn = function (x, y) {
121 | ++i;
122 | var p = new Bluebird(function (res) {
123 | setTimeout(function () { res(x + y); }, 100);
124 | });
125 | p.cancel();
126 | return p;
127 | };
128 |
129 | mfn = memoize(fn, { promise: true });
130 |
131 | mfn(3, 7).done(a.never, function (err) {
132 | a.throws(function () { throw err; }, Bluebird.CancellationError, "Result #1");
133 | });
134 |
135 | mfn(5, 8).done(a.never, function (err) {
136 | a.throws(function () { throw err; }, Bluebird.CancellationError, "Result B #2");
137 | });
138 |
139 | setTimeout(function () {
140 | a(i, 2, "Called #2");
141 |
142 | mfn(3, 7).done(a.never, function (err) {
143 | a.throws(
144 | function () { throw err; }, Bluebird.CancellationError, "Again: Result"
145 | );
146 | });
147 |
148 | mfn(5, 8).done(a.never, function (err) {
149 | a.throws(
150 | function () { throw err; }, Bluebird.CancellationError,
151 | "Again B: Result"
152 | );
153 | });
154 |
155 | setTimeout(function (err) {
156 | a(i, 4, "Again Called #2");
157 | d();
158 | }, 10);
159 | }, 10);
160 | },
161 | Delayed: function (a, d) {
162 | var mfn, fn, i = 0;
163 | fn = function (x, y) {
164 | ++i;
165 | var p = new Bluebird(function (res) {
166 | setTimeout(function () { res(x + y); }, 100);
167 | });
168 | nextTick(function () { p.cancel(); }, 1);
169 | return p;
170 | };
171 |
172 | mfn = memoize(fn, { promise: true });
173 |
174 | mfn(3, 7).done(a.never, a.never);
175 |
176 | mfn(5, 8).done(a.never, a.never);
177 |
178 | setTimeout(function () {
179 | a(i, 2, "Called #2");
180 |
181 | mfn(3, 7).done(a.never, a.never);
182 |
183 | mfn(5, 8).done(a.never, a.never);
184 |
185 | setTimeout(function (err) {
186 | a(i, 4, "Again Called #2");
187 | d();
188 | }, 500);
189 | }, 500);
190 | },
191 | },
192 | "Primitive": {
193 | "Success": function (a, d) {
194 | var mfn, fn, i = 0;
195 | fn = function (x, y) {
196 | return new Promise(function (res) {
197 | ++i;
198 | res(x + y);
199 | });
200 | };
201 |
202 | mfn = memoize(fn, { promise: true, primitive: true });
203 |
204 | mfn(3, 7).done(function (res) { a(res, 10, "Result #1"); }, a.never);
205 |
206 | mfn(3, 7).done(function (res) { a(res, 10, "Result #2"); }, a.never);
207 |
208 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #1"); }, a.never);
209 |
210 | mfn(3, 7).done(function (res) { a(res, 10, "Result #3"); }, a.never);
211 |
212 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #2"); }, a.never);
213 |
214 | setTimeout(function () {
215 | a(i, 2, "Called #2");
216 |
217 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); }, a.never);
218 |
219 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); }, a.never);
220 |
221 | setTimeout(function () {
222 | a(i, 2, "Again Called #2");
223 |
224 | mfn.delete(3, 7);
225 |
226 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); }, a.never);
227 |
228 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); }, a.never);
229 |
230 | setTimeout(function () {
231 | a(i, 3, "Call After delete");
232 | d();
233 | }, 10);
234 | }, 10);
235 | }, 10);
236 | },
237 | "Error": function (a, d) {
238 | var mfn, fn, i = 0, e = new Error("Test");
239 | fn = function (x, y) {
240 | return new Promise(function (res, rej) {
241 | ++i;
242 | rej(e);
243 | });
244 | };
245 |
246 | mfn = memoize(fn, { promise: "done", primitive: true });
247 |
248 | mfn(3, 7).done(a.never, function (err) { a(err, e, "Result #1"); });
249 |
250 | mfn(5, 8).done(a.never, function (err) { a(err, e, "Result B #2"); });
251 |
252 | setTimeout(function () {
253 | a(i, 2, "Called #2");
254 |
255 | mfn(3, 7).done(a.never, function (err) { a(err, e, "Again: Result"); });
256 |
257 | mfn(5, 8).done(a.never, function (err) { a(err, e, "Again B: Result"); });
258 |
259 | setTimeout(function (err) {
260 | a(i, 4, "Again Called #2");
261 | d();
262 | }, 10);
263 | }, 10);
264 | },
265 | "Primitive null arg case": function (a, d) {
266 | var mfn, x = {};
267 | mfn = memoize(
268 | function f(id) {
269 | return new Promise(function (res) { res(x); });
270 | },
271 | { promise: true, primitive: true }
272 | );
273 |
274 | mfn(null).done(function (res) {
275 | a.deep(res, x, "Args");
276 | d();
277 | }, a.never);
278 | },
279 | },
280 | "Sync Clear": function (a, d) {
281 | var mfn, fn;
282 | fn = function (x) {
283 | return new Promise(function (res) {
284 | nextTick(function () { res(x); });
285 | });
286 | };
287 |
288 | mfn = memoize(fn, { promise: true });
289 |
290 | mfn(1).done(function (res) { a(res, 1, "First"); }, a.never);
291 |
292 | mfn(2).done(function (res) {
293 | a(res, 2, "Second");
294 | d();
295 | }, a.never);
296 | },
297 | "Sync Clear: Primitive": function (a, d) {
298 | var mfn, fn;
299 | fn = function (x) {
300 | return new Promise(function (res) {
301 | nextTick(function () { res(x); });
302 | });
303 | };
304 |
305 | mfn = memoize(fn, { promise: true, primitive: true });
306 |
307 | mfn(1).done(function (res) { a(res, 1, "First"); }, a.never);
308 |
309 | mfn(2).done(function (res) {
310 | a(res, 2, "Second");
311 | d();
312 | }, a.never);
313 | },
314 | };
315 | };
316 |
--------------------------------------------------------------------------------
/test/ext/ref-counter.js:
--------------------------------------------------------------------------------
1 | /* eslint max-lines: 0, id-length: 0, no-undef: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..")
6 | , nextTick = require("next-tick")
7 | , Promise = require("plain-promise");
8 |
9 | module.exports = function () {
10 | return {
11 | "Regular": function (a) {
12 | var i = 0
13 | , fn = function (x, y, z) {
14 | ++i;
15 | return x + y + z;
16 | }
17 | , mfn;
18 | mfn = memoize(fn, { refCounter: true });
19 | a(mfn.deleteRef(3, 5, 7), null, "Delete before");
20 | a(mfn(3, 5, 7), 15, "Initial");
21 | a(mfn(3, 5, 7), 15, "Cache");
22 | a(mfn.deleteRef(3, 5, 7), false, "Delete #1");
23 | mfn(3, 5, 7);
24 | a(mfn.deleteRef(3, 5, 7), false, "Delete #2");
25 | mfn(3, 5, 7);
26 | a(mfn.deleteRef(3, 5, 7), false, "Delete #3");
27 | mfn(3, 5, 7);
28 | a(i, 1, "Not deleteed");
29 | a(mfn.deleteRef(3, 5, 7), false, "Delete #4");
30 | a(mfn.deleteRef(3, 5, 7), true, "Delete final");
31 | mfn(3, 5, 7);
32 | a(i, 2, "Restarted");
33 | mfn(3, 5, 7);
34 | a(i, 2, "Cached again");
35 | },
36 | "Regular: Async": function (a, d) {
37 | var mfn, fn, u = {}, i = 0;
38 | fn = function (x, y, cb) {
39 | nextTick(function () {
40 | ++i;
41 | cb(null, x + y);
42 | });
43 | return u;
44 | };
45 |
46 | mfn = memoize(fn, { async: true, refCounter: true });
47 |
48 | a(mfn.deleteRef(3, 7), null, "Delete ref before");
49 |
50 | a(
51 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #1"); }), u,
52 | "Initial"
53 | );
54 | a(
55 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #2"); }), u,
56 | "Initial #2"
57 | );
58 | a(
59 | mfn(5, 8, function (err, res) { a.deep([err, res], [null, 13], "Result B #1"); }),
60 | u, "Initial #2"
61 | );
62 | a(
63 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #3"); }), u,
64 | "Initial #2"
65 | );
66 | a(
67 | mfn(5, 8, function (err, res) { a.deep([err, res], [null, 13], "Result B #2"); }),
68 | u, "Initial #3"
69 | );
70 |
71 | nextTick(function () {
72 | a(i, 2, "Called #2");
73 |
74 | a(
75 | mfn(3, 7, function (err, res) {
76 | a.deep([err, res], [null, 10], "Again: Result");
77 | }),
78 | u, "Again: Initial"
79 | );
80 | a(
81 | mfn(5, 8, function (err, res) {
82 | a.deep([err, res], [null, 13], "Again B: Result");
83 | }),
84 | u, "Again B: Initial"
85 | );
86 |
87 | nextTick(function () {
88 | a(i, 2, "Again Called #2");
89 |
90 | a(mfn.deleteRef(3, 7), false, "Delete ref #1");
91 | a(mfn.deleteRef(3, 7), false, "Delete ref #2");
92 | a(mfn.deleteRef(3, 7), false, "Delete ref #3");
93 | a(mfn.deleteRef(3, 7), true, "Delete ref Final");
94 |
95 | a(
96 | mfn(3, 7, function (err, res) {
97 | a.deep([err, res], [null, 10], "Again: Result");
98 | }),
99 | u, "Again: Initial"
100 | );
101 | a(
102 | mfn(5, 8, function (err, res) {
103 | a.deep([err, res], [null, 13], "Again B: Result");
104 | }),
105 | u, "Again B: Initial"
106 | );
107 |
108 | nextTick(function () {
109 | a(i, 3, "Call After delete");
110 | d();
111 | });
112 | });
113 | });
114 | },
115 | "Regular: Promise": function (a, d) {
116 | var mfn, fn, i = 0;
117 | fn = function (x, y) {
118 | ++i;
119 | return new Promise(function (res) { res(x + y); });
120 | };
121 |
122 | mfn = memoize(fn, { promise: true, refCounter: true });
123 |
124 | a(mfn.deleteRef(3, 7), null, "Delete ref before");
125 |
126 | mfn(3, 7).done(function (res) { a(res, 10, "Result #1"); });
127 | mfn(3, 7).done(function (res) { a(res, 10, "Result #2"); });
128 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #1"); });
129 | mfn(3, 7).done(function (res) { a(res, 10, "Result #3"); });
130 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #2"); });
131 |
132 | setTimeout(function () {
133 | a(i, 2, "Called #2");
134 |
135 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); });
136 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); });
137 |
138 | setTimeout(function () {
139 | a(i, 2, "Again Called #2");
140 |
141 | a(mfn.deleteRef(3, 7), false, "Delete ref #1");
142 | a(mfn.deleteRef(3, 7), false, "Delete ref #2");
143 | a(mfn.deleteRef(3, 7), false, "Delete ref #3");
144 | a(mfn.deleteRef(3, 7), true, "Delete ref Final");
145 |
146 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); });
147 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); });
148 |
149 | setTimeout(function () {
150 | a(i, 3, "Call After delete");
151 | d();
152 | }, 10);
153 | }, 10);
154 | }, 10);
155 | },
156 | "Primitive": function (a) {
157 | var i = 0
158 | , fn = function (x, y, z) {
159 | ++i;
160 | return x + y + z;
161 | }
162 | , mfn;
163 | mfn = memoize(fn, { primitive: true, refCounter: true });
164 | a(mfn.deleteRef(3, 5, 7), null, "Delete before");
165 | a(mfn(3, 5, 7), 15, "Initial");
166 | a(mfn(3, 5, 7), 15, "Cache");
167 | a(mfn.deleteRef(3, 5, 7), false, "Delete #1");
168 | mfn(3, 5, 7);
169 | a(mfn.deleteRef(3, 5, 7), false, "Delete #2");
170 | mfn(3, 5, 7);
171 | a(mfn.deleteRef(3, 5, 7), false, "Delete #3");
172 | mfn(3, 5, 7);
173 | a(i, 1, "Not deleteed");
174 | a(mfn.deleteRef(3, 5, 7), false, "Delete #4");
175 | a(mfn.deleteRef(3, 5, 7), true, "Delete final");
176 | mfn(3, 5, 7);
177 | a(i, 2, "Restarted");
178 | mfn(3, 5, 7);
179 | a(i, 2, "Cached again");
180 | },
181 | "Primitive: Async": function (a, d) {
182 | var mfn, fn, u = {}, i = 0;
183 | fn = function (x, y, cb) {
184 | nextTick(function () {
185 | ++i;
186 | cb(null, x + y);
187 | });
188 | return u;
189 | };
190 |
191 | mfn = memoize(fn, { async: true, primitive: true, refCounter: true });
192 |
193 | a(mfn.deleteRef(3, 7), null, "Delete ref before");
194 |
195 | a(
196 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #1"); }), u,
197 | "Initial"
198 | );
199 | a(
200 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #2"); }), u,
201 | "Initial #2"
202 | );
203 | a(
204 | mfn(5, 8, function (err, res) { a.deep([err, res], [null, 13], "Result B #1"); }),
205 | u, "Initial #2"
206 | );
207 | a(
208 | mfn(3, 7, function (err, res) { a.deep([err, res], [null, 10], "Result #3"); }), u,
209 | "Initial #2"
210 | );
211 | a(
212 | mfn(5, 8, function (err, res) { a.deep([err, res], [null, 13], "Result B #2"); }),
213 | u, "Initial #3"
214 | );
215 |
216 | nextTick(function () {
217 | a(i, 2, "Called #2");
218 |
219 | a(
220 | mfn(3, 7, function (err, res) {
221 | a.deep([err, res], [null, 10], "Again: Result");
222 | }),
223 | u, "Again: Initial"
224 | );
225 | a(
226 | mfn(5, 8, function (err, res) {
227 | a.deep([err, res], [null, 13], "Again B: Result");
228 | }),
229 | u, "Again B: Initial"
230 | );
231 |
232 | nextTick(function () {
233 | a(i, 2, "Again Called #2");
234 |
235 | a(mfn.deleteRef(3, 7), false, "Delete ref #1");
236 | a(mfn.deleteRef(3, 7), false, "Delete ref #2");
237 | a(mfn.deleteRef(3, 7), false, "Delete ref #3");
238 | a(mfn.deleteRef(3, 7), true, "Delete ref Final");
239 |
240 | a(
241 | mfn(3, 7, function (err, res) {
242 | a.deep([err, res], [null, 10], "Again: Result");
243 | }),
244 | u, "Again: Initial"
245 | );
246 | a(
247 | mfn(5, 8, function (err, res) {
248 | a.deep([err, res], [null, 13], "Again B: Result");
249 | }),
250 | u, "Again B: Initial"
251 | );
252 |
253 | nextTick(function () {
254 | a(i, 3, "Call After delete");
255 | d();
256 | });
257 | });
258 | });
259 | },
260 | "Primitive: Promise": function (a, d) {
261 | var mfn, fn, i = 0;
262 | fn = function (x, y) {
263 | ++i;
264 | return new Promise(function (res) { res(x + y); });
265 | };
266 |
267 | mfn = memoize(fn, { promise: true, primitive: true, refCounter: true });
268 |
269 | a(mfn.deleteRef(3, 7), null, "Delete ref before");
270 |
271 | mfn(3, 7).done(function (res) { a(res, 10, "Result #1"); });
272 | mfn(3, 7).done(function (res) { a(res, 10, "Result #2"); });
273 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #1"); });
274 | mfn(3, 7).done(function (res) { a(res, 10, "Result #3"); });
275 | mfn(5, 8).done(function (res) { a(res, 13, "Result B #2"); });
276 |
277 | setTimeout(function () {
278 | a(i, 2, "Called #2");
279 |
280 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); });
281 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); });
282 |
283 | setTimeout(function () {
284 | a(i, 2, "Again Called #2");
285 |
286 | a(mfn.deleteRef(3, 7), false, "Delete ref #1");
287 | a(mfn.deleteRef(3, 7), false, "Delete ref #2");
288 | a(mfn.deleteRef(3, 7), false, "Delete ref #3");
289 | a(mfn.deleteRef(3, 7), true, "Delete ref Final");
290 |
291 | mfn(3, 7).done(function (res) { a(res, 10, "Again: Result"); });
292 | mfn(5, 8).done(function (res) { a(res, 13, "Again B: Result"); });
293 |
294 | setTimeout(function () {
295 | a(i, 3, "Call After delete");
296 | d();
297 | }, 10);
298 | }, 10);
299 | }, 10);
300 | },
301 | };
302 | };
303 |
--------------------------------------------------------------------------------
/test/lib/configure-map.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var aFrom = require("es5-ext/array/from")
6 | , memoize = require("../..");
7 |
8 | module.exports = function () {
9 | return {
10 | "One arg": function (a) {
11 | var i = 0
12 | , fn = function (x) {
13 | ++i;
14 | return x;
15 | }
16 | , mfn
17 | , y = { toString: function () { return "foo"; } };
18 | mfn = memoize(fn, { primitive: true });
19 | a(mfn(y), y, "#1");
20 | a(mfn("foo"), y, "#2");
21 | a(i, 1, "Called once");
22 | },
23 | "No args": function (a) {
24 | var i = 0
25 | , fn = function () {
26 | ++i;
27 | return "foo";
28 | }
29 | , mfn
30 | , y = { toString: function () { return "foo"; } };
31 | mfn = memoize(fn);
32 | a(mfn._has(), false);
33 | a(mfn(), "foo", "#1");
34 | a(mfn._has(), true);
35 | mfn();
36 | a(i, 1, "Called once");
37 | },
38 | "Clear cache": function (a) {
39 | var i = 0
40 | , fn = function (x, y, z) {
41 | ++i;
42 | return x + y + z;
43 | }
44 | , mfn
45 | , y = { toString: function () { return "foo"; } };
46 | mfn = memoize(fn, { primitive: true });
47 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#1");
48 | a(mfn("foo", "bar", "zeta"), "foobarzeta", "#2");
49 | a(i, 1, "Called once");
50 | mfn.delete("foo", { toString: function () { return "bar"; } }, "zeta");
51 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#3");
52 | a(i, 2, "Called twice");
53 | },
54 | "_get": function (a) {
55 | var fn = function (x) { return x; }, mfn;
56 | mfn = memoize(fn);
57 | a(mfn._get("foo"), undefined);
58 | mfn("foo");
59 | a(mfn._get("foo"), "foo");
60 | },
61 | "_has": function (a) {
62 | var fn = function (x) { return x; }, mfn;
63 | mfn = memoize(fn);
64 | a(mfn._has("foo"), false);
65 | mfn("foo");
66 | a(mfn._has("foo"), true);
67 | },
68 | "Circular": function (a) {
69 | var i = 0, fn;
70 | fn = memoize(function (x) { if (++i < 2) fn(x); });
71 | a.throws(function () { fn("foo"); }, "CIRCULAR_INVOCATION");
72 |
73 | i = 0;
74 | fn = memoize(function (x, y) { if (++i < 2) fn(x, y); });
75 | a.throws(function () { fn("foo", "bar"); }, "CIRCULAR_INVOCATION");
76 | },
77 | "Resolvers": function () {
78 | var i = 0, fn, r;
79 | fn = memoize(
80 | function () {
81 | ++i;
82 | return arguments;
83 | },
84 | { length: 3, resolvers: [Boolean, String] }
85 | );
86 | return {
87 | "No args": function (a) {
88 | i = 0;
89 | a.deep(aFrom((r = fn())), [false, "undefined"], "First");
90 | a(fn(), r, "Second");
91 | a(fn(), r, "Third");
92 | a(i, 1, "Called once");
93 | },
94 | "One arg": function (a) {
95 | var fn = memoize(
96 | function (elo) {
97 | ++i;
98 | return arguments;
99 | },
100 | { resolvers: [Boolean] }
101 | );
102 | a.deep(aFrom((r = fn("elo"))), [true], "First");
103 | },
104 | "Some Args": function (a) {
105 | var x = {};
106 | i = 0;
107 | a.deep(aFrom((r = fn(0, 34, x, 45))), [false, "34", x, 45], "First");
108 | a(fn(0, 34, x, 22), r, "Second");
109 | a(fn(0, 34, x, false), r, "Third");
110 | a(i, 1, "Called once");
111 | return {
112 | Other: function (a) {
113 | a.deep(aFrom((r = fn(1, 34, x, 34))), [true, "34", x, 34], "Second");
114 | a(fn(1, 34, x, 89), r, "Third");
115 | a(i, 2, "Called once");
116 | },
117 | };
118 | },
119 | };
120 | },
121 | };
122 | };
123 |
--------------------------------------------------------------------------------
/test/lib/methods.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | var d = require("d")
6 | , memoize = require("../..");
7 |
8 | require("../ext/dispose");
9 | require("../ext/ref-counter");
10 |
11 | module.exports = function (t, a) {
12 | var value = [], obj = {};
13 | t = t(memoize);
14 | Object.defineProperties(
15 | obj,
16 | t({
17 | someFn: d(
18 | function (x, y) {
19 | a(this, obj);
20 | return x + y;
21 | },
22 | { refCounter: true, dispose: function (val) { value.push(val); } }
23 | ),
24 | })
25 | );
26 |
27 | obj = Object.create(obj);
28 | obj.someFn(3, 7);
29 | obj.someFn(5, 8);
30 | obj.someFn(12, 4);
31 | a.deep(value, [], "Pre");
32 | obj.someFn(5, 8);
33 | obj.someFn.deleteRef(5, 8);
34 | a.deep(value, [], "Pre");
35 | obj.someFn.deleteRef(5, 8);
36 | a.deep(value, [13], "#1");
37 | value = [];
38 | obj.someFn.deleteRef(12, 4);
39 | a.deep(value, [16], "#2");
40 |
41 | value = [];
42 | obj.someFn(77, 11);
43 | obj.someFn.clear();
44 | a.deep(value, [10, 88], "Clear");
45 | };
46 |
--------------------------------------------------------------------------------
/test/lib/registered-extensions.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = function (t, a) {
4 | require("../../ext/async");
5 | a(typeof t.async, "function");
6 | };
7 |
--------------------------------------------------------------------------------
/test/lib/resolve-length.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = function (t, a) {
4 | a(t(1, 2), 1, "Options");
5 | a(t(1, 2, true), 1, "Options: Async ");
6 | a(t(undefined, 2), 2, "Function");
7 | a(t(undefined, 2, true), 1, "Function: Async");
8 | a(t(undefined, undefined, false), 1, "Unknown");
9 | a(t(undefined, undefined, true), 1, "Unknown: async");
10 | };
11 |
--------------------------------------------------------------------------------
/test/lib/resolve-normalize.js:
--------------------------------------------------------------------------------
1 | /* eslint no-empty-function: 0 */
2 |
3 | "use strict";
4 |
5 | module.exports = function (t, a) {
6 | var fn = function () {}, resolved = t(fn);
7 | a.deep(resolved, { get: fn, set: fn });
8 | a.deep(t(resolved), { get: fn, set: fn });
9 | };
10 |
--------------------------------------------------------------------------------
/test/lib/resolve-resolve.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = function (t, a) {
4 | a.deep(t([String, null, Number])([23, "foo", "45", "elo"]), ["23", "foo", 45, "elo"]);
5 | };
6 |
--------------------------------------------------------------------------------
/test/lib/weak.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..");
6 |
7 | require("../ext/dispose");
8 | require("../ext/ref-counter");
9 |
10 | module.exports = function (t, a) {
11 | var value = [], obj = {}, memoized, count = 0, x, y, z;
12 | t = t(memoize);
13 | memoized = t(
14 | function (arg, x, y) {
15 | a(arg, obj);
16 | return x + y;
17 | },
18 | { refCounter: true, dispose: function (val) { value.push(val); } }
19 | );
20 |
21 | a(memoized(obj, 3, 7), 10);
22 | a(memoized(obj, 5, 8), 13);
23 | a(memoized(obj, 12, 4), 16);
24 | a.deep(value, [], "Pre");
25 | a(memoized(obj, 5, 8), 13);
26 | memoized.deleteRef(obj, 5, 8);
27 | a.deep(value, [], "Pre");
28 | memoized.deleteRef(obj, 5, 8);
29 | a.deep(value, [13], "#1");
30 | value = [];
31 | memoized.deleteRef(obj, 12, 4);
32 | a.deep(value, [16], "#2");
33 |
34 | value = [];
35 | memoized(obj, 77, 11);
36 |
37 | x = {};
38 | y = {};
39 | z = {};
40 | memoized = t(function (arg) { return ++count; });
41 | a(memoized(x), 1);
42 | a(memoized(y), 2);
43 | a(memoized(x), 1);
44 | a(memoized(z), 3);
45 | a(count, 3);
46 | };
47 |
--------------------------------------------------------------------------------
/test/methods-plain.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | var d = require("d");
6 |
7 | require("../ext/dispose");
8 | require("../ext/ref-counter");
9 |
10 | module.exports = function (t, a) {
11 | var value = [], obj = {};
12 | Object.defineProperties(
13 | obj,
14 | t({
15 | someFn: d(
16 | function (x, y) {
17 | a(this, obj);
18 | return x + y;
19 | },
20 | { refCounter: true, dispose: function (val) { value.push(val); } }
21 | ),
22 | })
23 | );
24 |
25 | obj = Object.create(obj);
26 | obj.someFn(3, 7);
27 | obj.someFn(5, 8);
28 | obj.someFn(12, 4);
29 | a.deep(value, [], "Pre");
30 | obj.someFn(5, 8);
31 | obj.someFn.deleteRef(5, 8);
32 | a.deep(value, [], "Pre");
33 | obj.someFn.deleteRef(5, 8);
34 | a.deep(value, [13], "#1");
35 | value = [];
36 | obj.someFn.deleteRef(12, 4);
37 | a.deep(value, [16], "#2");
38 |
39 | value = [];
40 | obj.someFn(77, 11);
41 | obj.someFn.clear();
42 | a.deep(value, [10, 88], "Clear all");
43 | };
44 |
--------------------------------------------------------------------------------
/test/methods.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | var d = require("d");
6 |
7 | module.exports = function (t, a) {
8 | var value = [], obj = {};
9 | Object.defineProperties(
10 | obj,
11 | t({
12 | someFn: d(
13 | function (x, y) {
14 | a(this, obj);
15 | return x + y;
16 | },
17 | { refCounter: true, dispose: function (val) { value.push(val); } }
18 | ),
19 | })
20 | );
21 |
22 | obj = Object.create(obj);
23 | obj.someFn(3, 7);
24 | obj.someFn(5, 8);
25 | obj.someFn(12, 4);
26 | a.deep(value, [], "Pre");
27 | obj.someFn(5, 8);
28 | obj.someFn.deleteRef(5, 8);
29 | a.deep(value, [], "Pre");
30 | obj.someFn.deleteRef(5, 8);
31 | a.deep(value, [13], "#1");
32 | value = [];
33 | obj.someFn.deleteRef(12, 4);
34 | a.deep(value, [16], "#2");
35 |
36 | value = [];
37 | obj.someFn(77, 11);
38 | obj.someFn.clear();
39 | a.deep(value, [10, 88], "Clear all");
40 | };
41 |
--------------------------------------------------------------------------------
/test/normalizers/get-1.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..");
6 |
7 | module.exports = {
8 | "": function (t, a) {
9 | var i = 0
10 | , fn = function (x) {
11 | ++i;
12 | return x;
13 | };
14 |
15 | fn = memoize(fn);
16 | return {
17 | "No arg": function () {
18 | i = 0;
19 | a(fn(), undefined, "First");
20 | a(fn(), undefined, "Second");
21 | a(fn(), undefined, "Third");
22 | a(i, 1, "Called once");
23 | },
24 | "Arg": function () {
25 | var x = {};
26 | i = 0;
27 | a(fn(x, 8), x, "First");
28 | a(fn(x, 4), x, "Second");
29 | a(fn(x, 2), x, "Third");
30 | a(i, 1, "Called once");
31 | },
32 | "Other Arg": function () {
33 | var x = {};
34 | i = 0;
35 | a(fn(x, 2), x, "First");
36 | a(fn(x, 9), x, "Second");
37 | a(fn(x, 3), x, "Third");
38 | a(i, 1, "Called once");
39 | },
40 | };
41 | },
42 | "Delete": function (a) {
43 | var i = 0, fn, mfn, x = {};
44 |
45 | fn = function (a, b, c) { return a + ++i; };
46 | mfn = memoize(fn, { length: 1 });
47 | a(mfn(3), 4, "Init");
48 | a(mfn(4, x, 1), 6, "Init #2");
49 | mfn.delete(4);
50 | a(mfn(3, x, 1), 4, "Cached");
51 | mfn(3, x, 1);
52 | a(i, 2, "Pre clear");
53 | mfn.delete(3, x, 1);
54 | a(i, 2, "After clear");
55 | a(mfn(3, x, 1), 6, "Reinit");
56 | a(i, 3, "Reinit count");
57 | a(mfn(3, x, 1), 6, "Reinit Cached");
58 | a(i, 3, "Reinit count");
59 | },
60 | };
61 |
--------------------------------------------------------------------------------
/test/normalizers/get-fixed.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..");
6 |
7 | module.exports = {
8 | "": function (a) {
9 | var i = 0
10 | , fn = function (x, y, z) {
11 | ++i;
12 | return [x, y, z];
13 | }
14 | , r;
15 |
16 | fn = memoize(fn);
17 | return {
18 | "No args": function () {
19 | i = 0;
20 | a.deep((r = fn()), [undefined, undefined, undefined], "First");
21 | a(fn(), r, "Second");
22 | a(fn(), r, "Third");
23 | a(i, 1, "Called once");
24 | },
25 | "Some Args": function () {
26 | var x = {};
27 | i = 0;
28 | a.deep((r = fn(x, 8)), [x, 8, undefined], "First");
29 | a(fn(x, 8), r, "Second");
30 | a(fn(x, 8), r, "Third");
31 | a(i, 1, "Called once");
32 | return {
33 | Other: function () {
34 | a.deep((r = fn(x, 5)), [x, 5, undefined], "Second");
35 | a(fn(x, 5), r, "Third");
36 | a(i, 2, "Called once");
37 | },
38 | };
39 | },
40 | "Full stuff": function () {
41 | var x = {};
42 | i = 0;
43 | a.deep((r = fn(x, 8, 23, 98)), [x, 8, 23], "First");
44 | a(fn(x, 8, 23, 43), r, "Second");
45 | a(fn(x, 8, 23, 9), r, "Third");
46 | a(i, 1, "Called once");
47 | return {
48 | Other: function () {
49 | a.deep((r = fn(x, 23, 8, 13)), [x, 23, 8], "Second");
50 | a(fn(x, 23, 8, 22), r, "Third");
51 | a(i, 2, "Called once");
52 | },
53 | };
54 | },
55 | };
56 | },
57 | "Delete": function (a) {
58 | var i = 0, fn, mfn, x = {};
59 |
60 | fn = function (a, b, c) { return a + ++i; };
61 | mfn = memoize(fn);
62 | a(mfn(3, x, 1), 4, "Init");
63 | a(mfn(4, x, 1), 6, "Init #2");
64 | mfn.delete(4, x, 1);
65 | a(mfn(3, x, 1), 4, "Cached");
66 | mfn(3, x, 1);
67 | a(i, 2, "Pre clear");
68 | mfn.delete(3, x, 1);
69 | a(i, 2, "After clear");
70 | a(mfn(3, x, 1), 6, "Reinit");
71 | a(i, 3, "Reinit count");
72 | a(mfn(3, x, 1), 6, "Reinit Cached");
73 | a(i, 3, "Reinit count");
74 | },
75 | "Clear": function (a) {
76 | var i = 0, fn, x = {};
77 |
78 | fn = function () {
79 | ++i;
80 | return arguments;
81 | };
82 |
83 | fn = memoize(fn, { length: 3 });
84 | fn(1, x, 3);
85 | fn(1, x, 4);
86 | fn(1, x, 3);
87 | fn(1, x, 4);
88 | a(i, 2, "Pre clear");
89 | fn.clear();
90 | fn(1, x, 3);
91 | fn(1, x, 4);
92 | fn(1, x, 3);
93 | fn(1, x, 4);
94 | a(i, 4, "After clear");
95 | },
96 | };
97 |
--------------------------------------------------------------------------------
/test/normalizers/get-primitive-fixed.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..");
6 |
7 | module.exports = {
8 | "": function (a) {
9 | var i = 0
10 | , fn = function (x, y, z) {
11 | ++i;
12 | return x + y + z;
13 | }
14 | , mfn
15 | , y = { toString: function () { return "foo"; } };
16 | mfn = memoize(fn, { primitive: true });
17 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#1");
18 | a(mfn("foo", "bar", "zeta"), "foobarzeta", "#2");
19 | a(i, 1, "Called once");
20 | },
21 | "Delete": function (a) {
22 | var i = 0
23 | , fn = function (x, y, z) {
24 | ++i;
25 | return x + y + z;
26 | }
27 | , mfn
28 | , y = { toString: function () { return "foo"; } };
29 | mfn = memoize(fn, { primitive: true });
30 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#1");
31 | a(mfn("foo", "bar", "zeta"), "foobarzeta", "#2");
32 | a(i, 1, "Called once");
33 | mfn.delete("foo", { toString: function () { return "bar"; } }, "zeta");
34 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#3");
35 | a(i, 2, "Called twice");
36 | },
37 | "Clear": function (a) {
38 | var i = 0, fn;
39 | fn = memoize(function (x) { if (++i < 2) fn(x); });
40 | a.throws(function () { fn("foo"); }, "CIRCULAR_INVOCATION");
41 |
42 | i = 0;
43 | fn = memoize(function (x, y) { if (++i < 2) fn(x, y); });
44 | a.throws(function () { fn("foo", "bar"); }, "CIRCULAR_INVOCATION");
45 | },
46 | };
47 |
--------------------------------------------------------------------------------
/test/normalizers/get.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | var aFrom = require("es5-ext/array/from")
6 | , memoize = require("../..");
7 |
8 | module.exports = function () {
9 | return {
10 | "": function (a) {
11 | var i = 0
12 | , fn = function () {
13 | ++i;
14 | return arguments;
15 | }
16 | , r;
17 |
18 | fn = memoize(fn, { length: false });
19 | return {
20 | "No args": function () {
21 | i = 0;
22 | a.deep(aFrom((r = fn())), [], "First");
23 | a(fn(), r, "Second");
24 | a(fn(), r, "Third");
25 | a(i, 1, "Called once");
26 | },
27 | "Some Args": function () {
28 | var x = {};
29 | i = 0;
30 | a.deep(aFrom((r = fn(x, 8))), [x, 8], "First");
31 | a(fn(x, 8), r, "Second");
32 | a(fn(x, 8), r, "Third");
33 | a(i, 1, "Called once");
34 | },
35 | "Many args": function () {
36 | var x = {};
37 | i = 0;
38 | a.deep(aFrom((r = fn(x, 8, 23, 98))), [x, 8, 23, 98], "First");
39 | a(fn(x, 8, 23, 98), r, "Second");
40 | a(fn(x, 8, 23, 98), r, "Third");
41 | a(i, 1, "Called once");
42 | },
43 | };
44 | },
45 | "Delete": function (a) {
46 | var i = 0, fn, mfn, x = {};
47 |
48 | fn = function (a, b, c) { return a + ++i; };
49 | mfn = memoize(fn, { length: false });
50 | a(mfn(3, x, 1), 4, "Init");
51 | a(mfn(4, x, 1), 6, "Init #2");
52 | mfn.delete(4, x, 1);
53 | a(mfn(3, x, 1), 4, "Cached");
54 | mfn(3, x, 1);
55 | a(i, 2, "Pre clear");
56 | mfn.delete(3, x, 1);
57 | a(i, 2, "After clear");
58 | a(mfn(3, x, 1), 6, "Reinit");
59 | a(i, 3, "Reinit count");
60 | a(mfn(3, x, 1), 6, "Reinit Cached");
61 | a(i, 3, "Reinit count");
62 | },
63 | };
64 | };
65 |
--------------------------------------------------------------------------------
/test/normalizers/primitive.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../..")
6 | , join = Array.prototype.join;
7 |
8 | module.exports = function (a) {
9 | var i = 0
10 | , fn = function () {
11 | ++i;
12 | return join.call(arguments, "|");
13 | }
14 | , y = { toString: function () { return "foo"; } }
15 | , mfn;
16 | mfn = memoize(fn, { primitive: true, length: false });
17 | a(mfn(y, "bar", "zeta"), "foo|bar|zeta", "#1");
18 | a(mfn("foo", "bar", "zeta"), "foo|bar|zeta", "#2");
19 | a(i, 1, "Called once");
20 | a(mfn(y, "bar"), "foo|bar", "#3");
21 | a(i, 2, "Called twice");
22 | a(mfn(y, "bar"), "foo|bar", "#4");
23 | a(i, 2, "Called twice #2");
24 | };
25 |
--------------------------------------------------------------------------------
/test/plain.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0 */
2 |
3 | "use strict";
4 |
5 | module.exports = function (t) {
6 | return {
7 | "": function (a) {
8 | var i = 0
9 | , fn = function (x) {
10 | ++i;
11 | return x;
12 | }
13 | , mfn
14 | , y = { toString: function () { return "foo"; } };
15 | mfn = t(fn, { primitive: true });
16 | a(typeof mfn, "function", "Returns");
17 | a(mfn.__memoized__, true, "Marked");
18 | a(t(mfn), mfn, "Do not memoize memoized");
19 | a(mfn(y), y, "#1");
20 | a(mfn("foo"), y, "#2");
21 | a(i, 1, "Called once");
22 | },
23 | "Clear cache": function (a) {
24 | var i = 0
25 | , fn = function (x, y, z) {
26 | ++i;
27 | return x + y + z;
28 | }
29 | , mfn
30 | , y = { toString: function () { return "foo"; } };
31 | mfn = t(fn, { primitive: true });
32 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#1");
33 | a(mfn("foo", "bar", "zeta"), "foobarzeta", "#2");
34 | a(i, 1, "Called once");
35 | mfn.delete("foo", { toString: function () { return "bar"; } }, "zeta");
36 | a(mfn(y, "bar", "zeta"), "foobarzeta", "#3");
37 | a(i, 2, "Called twice");
38 | },
39 | };
40 | };
41 |
--------------------------------------------------------------------------------
/test/profile.js:
--------------------------------------------------------------------------------
1 | /* eslint no-empty-function: 0 */
2 |
3 | "use strict";
4 |
5 | var memoize = require("../plain");
6 |
7 | module.exports = function (t, a) {
8 | memoize(function () {})();
9 | memoize(function () {}, { profileName: "test" })();
10 | a(typeof t.statistics, "object", "Access to statistics");
11 | a(Object.keys(t.statistics).length, 2, "Statistics collected including named function");
12 | a(typeof t.log, "function", "Access to log function");
13 | a(typeof t.log(), "string", "Log outputs string");
14 | };
15 |
--------------------------------------------------------------------------------
/test/weak-plain.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | require("../ext/dispose");
6 | require("../ext/ref-counter");
7 |
8 | module.exports = function (t, a) {
9 | var value = [], obj = {}, memoized, count = 0, x, y, z;
10 | memoized = t(
11 | function (arg, x, y) {
12 | a(arg, obj);
13 | return x + y;
14 | },
15 | { refCounter: true, dispose: function (val) { value.push(val); } }
16 | );
17 |
18 | a(memoized(obj, 3, 7), 10);
19 | a(memoized(obj, 5, 8), 13);
20 | a(memoized(obj, 12, 4), 16);
21 | a.deep(value, [], "Pre");
22 | a(memoized(obj, 5, 8), 13);
23 | memoized.deleteRef(obj, 5, 8);
24 | a.deep(value, [], "Pre");
25 | memoized.deleteRef(obj, 5, 8);
26 | a.deep(value, [13], "#1");
27 | value = [];
28 | memoized.deleteRef(obj, 12, 4);
29 | a.deep(value, [16], "#2");
30 |
31 | value = [];
32 | memoized(obj, 77, 11);
33 |
34 | x = {};
35 | y = {};
36 | z = {};
37 | memoized = t(function (arg) { return ++count; });
38 | a(memoized(x), 1);
39 | a(memoized(y), 2);
40 | a(memoized(x), 1);
41 | a(memoized(z), 3);
42 | a(count, 3);
43 | };
44 |
--------------------------------------------------------------------------------
/test/weak.js:
--------------------------------------------------------------------------------
1 | /* eslint id-length: 0, no-shadow: 0, no-unused-vars: 0 */
2 |
3 | "use strict";
4 |
5 | module.exports = function (t, a, d) {
6 | var value = [], obj = {}, memoized, count = 0, x, y, z;
7 | memoized = t(
8 | function (arg, x, y) {
9 | a(arg, obj);
10 | return x + y;
11 | },
12 | { refCounter: true, dispose: function (val) { value.push(val); } }
13 | );
14 |
15 | a(memoized(obj, 3, 7), 10);
16 | a(memoized(obj, 5, 8), 13);
17 | a(memoized(obj, 12, 4), 16);
18 | a.deep(value, [], "Pre");
19 | a(memoized(obj, 5, 8), 13);
20 | memoized.deleteRef(obj, 5, 8);
21 | a.deep(value, [], "Pre");
22 | memoized.deleteRef(obj, 5, 8);
23 | a.deep(value, [13], "#1");
24 | value = [];
25 | memoized.deleteRef(obj, 12, 4);
26 | a.deep(value, [16], "#2");
27 |
28 | value = [];
29 | memoized(obj, 77, 11);
30 |
31 | x = {};
32 | y = {};
33 | z = {};
34 | memoized = t(function (arg) { return ++count; });
35 | a(memoized(x), 1);
36 | a(memoized(y), 2);
37 | a(memoized(x), 1);
38 | a(memoized(z), 3);
39 | a(count, 3);
40 |
41 | count = 0;
42 | memoized = t(function (arg) { return ++count; }, { maxAge: 1 });
43 |
44 | memoized(obj);
45 | setTimeout(function () {
46 | memoized(obj);
47 | a(count, 2);
48 | d();
49 | }, 100);
50 | };
51 |
--------------------------------------------------------------------------------
/weak-plain.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = require("./lib/weak")(require("./plain"));
4 |
--------------------------------------------------------------------------------
/weak.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | module.exports = require("./lib/weak")(require("./"));
4 |
--------------------------------------------------------------------------------