{ "name": "memoizee", "version": "0.3.8", "description": "Memoize/cache function results", "author": { "name": "Mariusz Nowak", "email": "medikoo@medikoo.com", "url": "http://www.medikoo.com/" }, "keywords": [ "memoize", "memoizer", "cache", "memoization", "memo", "memcached", "hashing.", "storage", "caching", "memory", "gc", "weak", "garbage", "collector", "async" ], "repository": { "type": "git", "url": "git://github.com/medikoo/memoize.git" }, "dependencies": { "d": "~0.1.1", "es5-ext": "~0.10.4", "es6-weak-map": "~0.1.2", "event-emitter": "~0.3.1", "lru-queue": "0.1", "next-tick": "~0.2.2", "timers-ext": "0.1" }, "devDependencies": { "tad": "0.2.x", "xlint": "~0.2.1", "xlint-jslint-medikoo": "~0.1.2" }, "scripts": { "lint": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --no-cache --no-stream", "lint-console": "node node_modules/xlint/bin/xlint --linter=node_modules/xlint-jslint-medikoo/index.js --watch", "test": "node node_modules/tad/bin/tad" }, "license": "MIT", "readme": "# Memoize\n## Complete memoize/cache solution for JavaScript\n\n_Originally derived from [es5-ext](https://github.com/medikoo/es5-ext) package._\n\nMemoization 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\n\n### Features\n\n* Works with any type of function arguments – __no serialization is needed__\n* Works with [__any length of function arguments__](#arguments-length). Length can be set as fixed or dynamic.\n* One of the [__fastest__](#benchmarks) available solutions.\n* Support for [__asynchronous functions__](#memoizing-asynchronous-functions)\n* [__Primitive mode__](#primitive-mode) which assures fast performance when arguments are conversible to strings.\n* [__WeakMap based mode__](#weak-map) for garbage collection friendly configuration\n* Can be configured [__for methods__](#memoizing-a-method) (when `this` counts in)\n* Cache [__can be cleared manually__](#manual-clean-up) or [__after specified timeout__](#expire-cache-after-given-period-of-time)\n* Cache size can be __[limited on LRU basis](#limiting-cache-size)__\n* Optionally [__accepts resolvers__](#resolvers) that normalize function arguments before passing them to underlying function.\n* Optional [__reference counter mode__](#reference-counter), that allows more sophisticated cache management\n* [__Profile tool__](#profiling--statistics) that provides valuable usage statistics\n* Covered by [__over 500 unit tests__](#tests-)\n\n### Installation\n\nIn your project path — __note the two `e`'s in `memoizee`:__\n\n\t$ npm install memoizee\n\n_`memoize` name was already taken, therefore project is published as `memoizee` on NPM._\n\nTo 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/)\n\n### Usage\n\n```javascript\nvar memoize = require('memoizee');\n\nvar fn = function (one, two, three) { /* ... */ };\n\nmemoized = memoize(fn);\n\nmemoized('foo', 3, 'bar');\nmemoized('foo', 3, 'bar'); // Cache hit\n```\n\n### Configuration\n\nAll below options can be applied in any combination\n\n#### Arguments length\n\nBy default fixed number of arguments that function take is assumed (it's read from function's `length` property) this can be overridden:\n\n```javascript\nmemoized = memoize(fn, { length: 2 });\n\nmemoized('foo'); // Assumed: 'foo', undefined\nmemoized('foo', undefined); // Cache hit\n\nmemoized('foo', 3, {}); // Third argument is ignored (but passed to underlying function)\nmemoized('foo', 3, 13); // Cache hit\n```\n\nDynamic _length_ behavior can be forced by setting _length_ to `false`, that means memoize will work with any number of arguments.\n\n```javascript\nmemoized = memoize(fn, { length: false });\n\nmemoized('foo');\nmemoized('foo'); // Cache hit\nmemoized('foo', undefined);\nmemoized('foo', undefined); // Cache hit\n\nmemoized('foo', 3, {});\nmemoized('foo', 3, 13);\nmemoized('foo', 3, 13); // Cache hit\n```\n\n#### Primitive mode\n\nIf 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 convertion. __Mind that this mode will work correctly only if stringified arguments produce unique strings.__\n\n```javascript\nmemoized = memoize(fn, { primitive: true });\n\nmemoized('/path/one');\nmemoized('/path/one'); // Cache hit\n```\n\n#### Resolvers\n\nWhen 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:\n\n```javascript\nmemoized = memoize(fn, { length: 2, resolvers: [String, Boolean] });\n\nmemoized(12, [1,2,3].length);\nmemoized(\"12\", true); // Cache hit\nmemoized({ toString: function () { return \"12\"; } }, {}); // Cache hit\n```\n\n__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`.\n\nSimilarly __if you want to memoize functions by their code representation not by their objects, you should use primitive mode__.\n\n#### Memoizing asynchronous functions\n\nWith _async_ option we indicate that we memoize asynchronous function. \nOperations that result with an error are not cached.\n\n```javascript\nafn = function (a, b, cb) {\n setTimeout(function () {\n cb(null, a + b);\n }, 200);\n};\nmemoized = memoize(afn, { async: true });\n\nmemoized(3, 7, function (err, res) {\n memoized(3, 7, function (err, res) {\n // Cache hit\n });\n});\n\nmemoized(3, 7, function (err, res) {\n // Cache hit\n});\n```\n\n#### Memoizing a methods\n\nWhen we are defining a prototype, we may want to define method that will memoize it's results in relation to each instance. Basic way to obtain that would be:\n\n```javascript\nvar Foo = function () {\n this.bar = memoize(this.bar.bind(this), { someOption: true });\n // ... constructor logic\n};\nFoo.prototype.bar = function () {\n // ... method logic\n};\n```\n\nThere's a lazy methods descriptor generator provided:\n\n```javascript\nvar d = require('d');\nvar memoizeMethods = require('memoizee/methods');\n\nvar Foo = function () {\n // ... constructor logic\n};\nObject.defineProperties(Foo.prototype, memoizeMethods({\n bar: d(function () {\n // ... method logic\n }, { someOption: true })\n}));\n```\n\n#### WeakMap based configurations\n\nIn that 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.\n\nThis mode works only for functions of which first argument is expected to be an object. \nIt can be combined with other options mentioned across documentation. However due to WeakMap specificity global clear is not possible with [dispose callback](#registering-dispose-callback) registered.\n\n```javascript\nvar memoize = require('memoizee/weak');\n\nvar memoized = memoize(function (obj) { return Object.keys(obj); });\n\nvar obj = { foo: true, bar: false };\nmemoized(obj);\nmemoized(obj); // Cache hit\n```\n\n#### Cache handling\n\n##### Manual clean up:\n\nDelete data for particular call.\n\n```javascript\nmemoized.delete('foo', true);\n```\n\nArguments passed to `delete` are treated with same rules as input arguments passed to function\n\nClear all cached data:\n\n```javascript\nmemoized.clear();\n```\n\n##### Expire cache after given period of time\n\nWith _maxAge_ option we can ensure that cache for given call is cleared after predefined period of time (in milliseconds)\n\n```javascript\nmemoized = memoize(fn, { maxAge: 1000 }); // 1 second\n\nmemoized('foo', 3);\nmemoized('foo', 3); // Cache hit\nsetTimeout(function () {\n memoized('foo', 3); // No longer in cache, re-executed\n memoized('foo', 3); // Cache hit\n}, 2000);\n```\n\nAdditionally 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:\n\n```javascript\nmemoized = memoize(fn, { maxAge: 1000, preFetch: true }); // Defaults to 0.33\n\nmemoized('foo', 3);\nmemoized('foo', 3); // Cache hit\n\nsetTimeout(function () {\n memoized('foo', 3); // Cache hit\n}, 500);\n\nsetTimeout(function () {\n memoized('foo', 3); // Cache hit, silently pre-fetched in next tick\n}, 800);\n\nsetTimeout(function () {\n memoized('foo', 3); // Cache hit\n}, 1300);\n```\n\n_Pre-fetch_ timespan can be customized:\n\n```javascript\nmemoized = memoize(fn, { maxAge: 1000, preFetch: 0.6 });\n\nmemoized('foo', 3);\nmemoized('foo', 3); // Cache hit\n\nsetTimeout(function () {\n memoized('foo', 3); // Cache hit, silently pre-fetched in next tick\n}, 500);\n\nsetTimeout(function () {\n memoized('foo', 3); // Cache hit\n}, 1300);\n```\n\n_Thanks [@puzrin](https://github.com/puzrin) for helpful suggestions concerning this functionality_\n\n##### Reference counter\n\nWe can track number of references returned from cache, and manually delete them. When last reference is cleared, cache is purged automatically:\n\n```javascript\nmemoized = memoize(fn, { refCounter: true });\n\nmemoized('foo', 3); // refs: 1\nmemoized('foo', 3); // Cache hit, refs: 2\nmemoized('foo', 3); // Cache hit, refs: 3\nmemoized.deleteRef('foo', 3); // refs: 2\nmemoized.deleteRef('foo', 3); // refs: 1\nmemoized.deleteRef('foo', 3); // refs: 0, Cache purged for 'foo', 3\nmemoized('foo', 3); // Re-executed, refs: 1\n```\n\n##### Limiting cache size\n\nWith _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\n\n```javascript\nmemoized = memoize(fn, { max: 2 });\n\nmemoized('foo', 3);\nmemoized('bar', 7);\nmemoized('foo', 3); // Cache hit\nmemoized('bar', 7); // Cache hit\nmemoized('lorem', 11); // Cache cleared for 'foo', 3\nmemoized('bar', 7); // Cache hit\nmemoized('foo', 3); // Re-executed, Cache cleared for 'lorem', 11\nmemoized('lorem', 11); // Re-executed, Cache cleared for 'bar', 7\nmemoized('foo', 3); // Cache hit\nmemoized('bar', 7); // Re-executed, Cache cleared for 'lorem', 11\n```\n\n##### Registering dispose callback\n\nYou can register callback that is called on each value being removed from cache:\n\n```javascript\nmemoized = memoize(fn, { dispose: function (value) { /*…*/ } });\n\nvar foo3 = memoized('foo', 3);\nvar bar7 = memoized('bar', 7);\nmemoized.clear('foo', 3); // Dispose called with foo3 value\nmemoized.clear('bar', 7); // Dispose called with bar7 value\n```\n\n### Benchmarks\n\nSimple 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:\n\n\t$ npm install underscore lodash lru-cache\n\nExample output taken under Node v0.8.26 on 2008 MBP Pro:\n\n```\nFibonacci 3000 x10:\n\n1: 25ms Memoizee (primitive mode)\n2: 28ms Underscore\n3: 34ms lru-cache LRU (max: 1000)\n4: 65ms Lo-dash\n5: 94ms Memoizee (primitive mode) LRU (max: 1000)\n6: 262ms Memoizee (object mode) LRU (max: 1000)\n7: 280ms Memoizee (object mode)\n```\n\n### Profiling & Statistics\n\nIf 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.\n\n__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__\n\n```javascript\nvar memProfile = require('memoizee/profile');\n```\n\nAccess statistics at any time:\n\n```javascript\nmemProfile.statistics; // Statistcs accessible for programmatical use\nconsole.log(memProfile.log()); // Output statistics data in readable form\n```\n\nExample console output:\n\n```\n------------------------------------------------------------\nMemoize statistics:\n\n Init Cache %Cache Source location\n11604 35682 75.46 (all)\n 2112 19901 90.41 at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:276:12\n 2108 9087 81.17 at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:293:10\n 6687 2772 29.31 at /Users/medikoo/Projects/_packages/next/lib/fs/watch.js:125:9\n 697 3922 84.91 at /Users/medikoo/Projects/_packages/next/lib/fs/is-ignored.js:277:15\n------------------------------------------------------------\n```\n\n* _Init_ – Initial hits\n* _Cache_ – Cache hits\n* _%Cache_ – What's the percentage of cache hits (of all function calls)\n* _Source location_ – Where in the source code given memoization was initialized\n\n### Tests [![Build Status](https://travis-ci.org/medikoo/memoize.svg)](https://travis-ci.org/medikoo/memoize)\n\n\t$ npm test\n\n### Contributors\n\n* [@puzrin](https://github.com/puzrin) (Vitaly Puzrin)\n * Proposal and help with coining right _pre-fetch_ logic for [_maxAge_](https://github.com/medikoo/memoize#expire-cache-after-given-period-of-time) variant\n", "readmeFilename": "README.md", "bugs": { "url": "https://github.com/medikoo/memoize/issues" }, "homepage": "https://github.com/medikoo/memoize", "_id": "memoizee@0.3.8", "_shasum": "b5faf419f02fafe3c2cc1cf5d3907c210fc7efdc", "_from": "memoizee@0.3.x", "_resolved": "https://registry.npmjs.org/memoizee/-/memoizee-0.3.8.tgz" }