{"name":"mem","version":"6.0.0","description":"Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input","license":"MIT","repository":{"type":"git","url":"git+https://github.com/sindresorhus/mem.git"},"author":{"name":"Sindre Sorhus","email":"sindresorhus@gmail.com","url":"sindresorhus.com"},"engines":{"node":">=8"},"scripts":{"test":"xo && ava && tsd"},"keywords":["memoize","function","mem","memoization","cache","caching","optimize","performance","ttl","expire","promise"],"dependencies":{"map-age-cleaner":"^0.1.3","mimic-fn":"^3.0.0"},"devDependencies":{"ava":"^2.4.0","delay":"^4.1.0","serialize-javascript":"^2.1.0","tsd":"^0.10.0","xo":"^0.25.3"},"gitHead":"b154f53ad72ac76277c0cc2844febf1cd2df1795","bugs":{"url":"https://github.com/sindresorhus/mem/issues"},"homepage":"https://github.com/sindresorhus/mem#readme","_id":"mem@6.0.0","_nodeVersion":"12.13.0","_npmVersion":"6.12.0","_npmUser":{"name":"sindresorhus","email":"sindresorhus@gmail.com"},"dist":{"integrity":"sha512-1zHBKMg0Xd4yw3EQju6cjJiNtPomak7aNkuJx19QihMco09icTTsLZtVvxfxBxQH/NNvjtA1skR9lDlvkdW46g==","shasum":"f79bb110b90b688a2d1468566e66a911794abee5","tarball":"http://registry-npm.ywwl.com/mem/download/mem-6.0.0.tgz","fileCount":5,"unpackedSize":10414,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdySiRCRA9TVsSAnZWagAApMIQAIVALLVijqn6UMnu5XB9\nPGQBFSMU4FAAnnKCOj4lJT4whFHSFq1q3ZM3RbsrO0hklaZ7zmSBS7WenxsX\nc4W+GNlq/J04SpvgSw7/TEJdTWs85GqUDSuit8vtrLZvGdirJ6YN6MMdEF7a\nc79BEth2MdDcRgzmQtk0/1uQdbpbuhNfdpa8Gctcw0h9QeqcOj7tvUf6e3cw\nipTzMUwfhWt3p0ikfJLRTt6J+z8kZWGXZOzMNtWB2M8sxHm7Hnoj9+xKLLWd\nQt82tZcBbBh5cSKLCoEI78UqzzUQkbHN6GhxB2sOtAUEzYiJLpQDHWJ9NS+B\nCxEM+noUenh9sIBwMv4d7Wok+vWWIKSNUHnQ/7gObbvCD+0LFWir13k4K71v\n3+8eu8NKpQ0KEXE6/vpYj36i3wFVn3JIi03TFijoDvFyBVt9D23R8P3SVMOi\nhMR0niBp9IsMMwg+k1rhTSZdxbdrDK0aiivZmKLL6RvFj9/UxptUPHN5dvRN\nm7z1owYwhejspZLeV4X+U0H0xnV8I8Sx5pcXJdMyYI4zbpgTHqwogZGwHWHr\nRp5IeOZsxOHpC2AUvryww6Ohig19U+6ImRx6pq6uEKw2vpsd+xC9ecd67PT8\nwP1DYP1msfSupdIJoelMoDsdWlwFwG1yiEu0NXxjIRCd+SPfPiv8W9Wq2geS\noAR7\r\n=K9pr\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC4im2lo7KZ9pi4eAhhapv1BkH03pkScC5mlvIfV+F/9AIhAObZubyDQFiS3ez+OhQi1wyQRWMTjlzSMoNCl21wBUuI"}],"size":3864,"noattachment":false,"key":"/mem/-/mem-6.0.0.tgz"},"maintainers":[{"name":"sindresorhus","email":"sindresorhus@gmail.com"}],"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/mem_6.0.0_1573464208617_0.15677627413666806"},"_hasShrinkwrap":false,"readme":"# mem\n\n> [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input\n\nMemory is automatically released when an item expires or the cache is cleared.\n\n<!-- Please keep this section in sync with https://github.com/sindresorhus/p-memoize/blob/main/readme.md -->\n\nBy default, **only the memoized function's first argument is considered** via strict equality comparison. If you need to cache multiple arguments or cache `object`s *by value*, have a look at alternative [caching strategies](#caching-strategy) below.\n\nIf you want to memoize Promise-returning functions (like `async` functions), you might be better served by [p-memoize](https://github.com/sindresorhus/p-memoize).\n\n## Install\n\n```\n$ npm install mem\n```\n\n## Usage\n\n```js\nimport mem from 'mem';\n\nlet index = 0;\nconst counter = () => ++index;\nconst memoized = mem(counter);\n\nmemoized('foo');\n//=> 1\n\n// Cached as it's the same argument\nmemoized('foo');\n//=> 1\n\n// Not cached anymore as the argument changed\nmemoized('bar');\n//=> 2\n\nmemoized('bar');\n//=> 2\n\n// Only the first argument is considered by default\nmemoized('bar', 'foo');\n//=> 2\n```\n\n##### Works well with Promise-returning functions\n\nBut you might want to use [p-memoize](https://github.com/sindresorhus/p-memoize) for more Promise-specific behaviors.\n\n```js\nimport mem from 'mem';\n\nlet index = 0;\nconst counter = async () => ++index;\nconst memoized = mem(counter);\n\nconsole.log(await memoized());\n//=> 1\n\n// The return value didn't increase as it's cached\nconsole.log(await memoized());\n//=> 1\n```\n\n```js\nimport mem from 'mem';\nimport got from 'got';\nimport delay from 'delay';\n\nconst memGot = mem(got, {maxAge: 1000});\n\nawait memGot('https://sindresorhus.com');\n\n// This call is cached\nawait memGot('https://sindresorhus.com');\n\nawait delay(2000);\n\n// This call is not cached as the cache has expired\nawait memGot('https://sindresorhus.com');\n```\n\n### Caching strategy\n\nBy default, only the first argument is compared via exact equality (`===`) to determine whether a call is identical.\n\n```js\nconst power = mem((a, b) => Math.power(a, b));\n\npower(2, 2); // => 4, stored in cache with the key 2 (number)\npower(2, 3); // => 4, retrieved from cache at key 2 (number), it's wrong\n```\n\nYou will have to use the `cache` and `cacheKey` options appropriate to your function. In this specific case, the following could work:\n\n```js\nconst power = mem((a, b) => Math.power(a, b), {\n  cacheKey: arguments_ => arguments_.join(',')\n});\n\npower(2, 2); // => 4, stored in cache with the key '2,2' (both arguments as one string)\npower(2, 3); // => 8, stored in cache with the key '2,3'\n```\n\nMore advanced examples follow.\n\n#### Example: Options-like argument\n\nIf your function accepts an object, it won't be memoized out of the box:\n\n```js\nconst heavyMemoizedOperation = mem(heavyOperation);\n\nheavyMemoizedOperation({full: true}); // Stored in cache with the object as key\nheavyMemoizedOperation({full: true}); // Stored in cache with the object as key, again\n// The objects look the same but for JS they're two different objects\n```\n\nYou might want to serialize or hash them, for example using `JSON.stringify` or something like [serialize-javascript](https://github.com/yahoo/serialize-javascript), which can also serialize `RegExp`, `Date` and so on.\n\n```js\nconst heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});\n\nheavyMemoizedOperation({full: true}); // Stored in cache with the key '[{\"full\":true}]' (string)\nheavyMemoizedOperation({full: true}); // Retrieved from cache\n```\n\nThe same solution also works if it accepts multiple serializable objects:\n\n```js\nconst heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});\n\nheavyMemoizedOperation('hello', {full: true}); // Stored in cache with the key '[\"hello\",{\"full\":true}]' (string)\nheavyMemoizedOperation('hello', {full: true}); // Retrieved from cache\n```\n\n#### Example: Multiple non-serializable arguments\n\nIf your function accepts multiple arguments that aren't supported by `JSON.stringify` (e.g. DOM elements and functions), you can instead extend the initial exact equality (`===`) to work on multiple arguments using [`many-keys-map`](https://github.com/fregante/many-keys-map):\n\n```js\nimport ManyKeysMap from 'many-keys-map';\n\nconst addListener = (emitter, eventName, listener) => emitter.on(eventName, listener);\n\nconst addOneListener = mem(addListener, {\n\tcacheKey: arguments_ => arguments_, // Use *all* the arguments as key\n\tcache: new ManyKeysMap() // Correctly handles all the arguments for exact equality\n});\n\naddOneListener(header, 'click', console.log); // `addListener` is run, and it's cached with the `arguments` array as key\naddOneListener(header, 'click', console.log); // `addListener` is not run again\naddOneListener(mainContent, 'load', console.log); // `addListener` is run, and it's cached with the `arguments` array as key\n```\n\nBetter yet, if your function’s arguments are compatible with `WeakMap`, you should use [`deep-weak-map`](https://github.com/futpib/deep-weak-map) instead of `many-keys-map`. This will help avoid memory leaks.\n\n## API\n\n### mem(fn, options?)\n\n#### fn\n\nType: `Function`\n\nFunction to be memoized.\n\n#### options\n\nType: `object`\n\n##### maxAge\n\nType: `number`\\\nDefault: `Infinity`\n\nMilliseconds until the cache expires.\n\n##### cacheKey\n\nType: `Function`\\\nDefault: `arguments_ => arguments_[0]`\\\nExample: `arguments_ => JSON.stringify(arguments_)`\n\nDetermines the cache key for storing the result based on the function arguments. By default, **only the first argument is considered**.\n\nA `cacheKey` function can return any type supported by `Map` (or whatever structure you use in the `cache` option).\n\nRefer to the [caching strategies](#caching-strategy) section for more information.\n\n##### cache\n\nType: `object`\\\nDefault: `new Map()`\n\nUse a different cache storage. Must implement the following methods: `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()`. You could for example use a `WeakMap` instead or [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.\n\nRefer to the [caching strategies](#caching-strategy) section for more information.\n\n### memDecorator(options)\n\nReturns a [decorator](https://github.com/tc39/proposal-decorators) to memoize class methods or static class methods.\n\nNotes:\n\n- Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);\n- Only [TypeScript’s decorators](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators) are supported, not [Babel’s](https://babeljs.io/docs/en/babel-plugin-proposal-decorators), which use a different version of the proposal;\n- Being an experimental feature, they need to be enabled with `--experimentalDecorators`; follow TypeScript’s docs.\n\n#### options\n\nType: `object`\n\nSame as options for `mem()`.\n\n```ts\nimport {memDecorator} from 'mem';\n\nclass Example {\n\tindex = 0\n\n\t@memDecorator()\n\tcounter() {\n\t\treturn ++this.index;\n\t}\n}\n\nclass ExampleWithOptions {\n\tindex = 0\n\n\t@memDecorator({maxAge: 1000})\n\tcounter() {\n\t\treturn ++this.index;\n\t}\n}\n```\n\n### memClear(fn)\n\nClear all cached data of a memoized function.\n\n#### fn\n\nType: `Function`\n\nMemoized function.\n\n## Tips\n\n### Cache statistics\n\nIf you want to know how many times your cache had a hit or a miss, you can make use of [stats-map](https://github.com/SamVerschueren/stats-map) as a replacement for the default cache.\n\n#### Example\n\n```js\nimport mem from 'mem';\nimport StatsMap from 'stats-map';\nimport got from 'got';\n\nconst cache = new StatsMap();\nconst memGot = mem(got, {cache});\n\nawait memGot('https://sindresorhus.com');\nawait memGot('https://sindresorhus.com');\nawait memGot('https://sindresorhus.com');\n\nconsole.log(cache.stats);\n//=> {hits: 2, misses: 1}\n```\n\n## Related\n\n- [p-memoize](https://github.com/sindresorhus/p-memoize) - Memoize promise-returning & async functions\n\n---\n\n<div align=\"center\">\n\t<b>\n\t\t<a href=\"https://tidelift.com/subscription/pkg/npm-mem?utm_source=npm-mem&utm_medium=referral&utm_campaign=readme\">Get professional support for this package with a Tidelift subscription</a>\n\t</b>\n\t<br>\n\t<sub>\n\t\tTidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.\n\t</sub>\n</div>\n","publish_time":1573464208762,"_cnpm_publish_time":1573464208762,"dist-tags":{"latest":"10.0.0","next":"7.0.0-3"}}