{"name":"mem","version":"7.0.0-2","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"},"funding":"https://github.com/sindresorhus/mem?sponsor=1","author":{"name":"Sindre Sorhus","email":"sindresorhus@gmail.com","url":"https://sindresorhus.com"},"engines":{"node":">=10"},"scripts":{"test":"xo && npm run build && ava","build":"del-cli dist && tsc","prepack":"npm run build"},"main":"dist","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/typescript":"^1.1.1","@sindresorhus/tsconfig":"^0.7.0","@types/serialize-javascript":"^4.0.0","ava":"^3.13.0","del-cli":"^3.0.1","delay":"^4.1.0","serialize-javascript":"^5.0.1","typescript":"^4.0.3","xo":"^0.33.1"},"ava":{"files":["test.ts"],"timeout":"1m","typescript":{"rewritePaths":{"./":"dist/"}}},"xo":{"rules":{"@typescript-eslint/no-var-requires":"off","@typescript-eslint/no-empty-function":"off"}},"readme":"# mem [![Build Status](https://travis-ci.org/sindresorhus/mem.svg?branch=master)](https://travis-ci.org/sindresorhus/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\nBy default, **only the first argument is considered** and it only works with [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). If you need to cache multiple arguments or cache `object`s *by value*, have a look at alternative [caching strategies](#caching-strategy) below.\n\n## Install\n\n```\n$ npm install mem\n```\n\n## Usage\n\n```js\nconst mem = require('mem');\n\nlet i = 0;\nconst counter = () => ++i;\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 fine with promise returning functions\n\n```js\nconst mem = require('mem');\n\nlet i = 0;\nconst counter = async () => ++i;\nconst memoized = mem(counter);\n\n(async () => {\n\tconsole.log(await memoized());\n\t//=> 1\n\n\t// The return value didn't increase as it's cached\n\tconsole.log(await memoized());\n\t//=> 1\n})();\n```\n\n```js\nconst mem = require('mem');\nconst got = require('got');\nconst delay = require('delay');\n\nconst memGot = mem(got, {maxAge: 1000});\n\n(async () => {\n\tawait memGot('https://sindresorhus.com');\n\n\t// This call is cached\n\tawait memGot('https://sindresorhus.com');\n\n\tawait delay(2000);\n\n\t// This call is not cached as the cache has expired\n\tawait memGot('https://sindresorhus.com');\n})();\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\nconst ManyKeysMap = require('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### mem.clear(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\nconst mem = require('mem');\nconst StatsMap = require('stats-map');\nconst got = require('got');\n\nconst cache = new StatsMap();\nconst memGot = mem(got, {cache});\n\n(async () => {\n\tawait memGot('https://sindresorhus.com');\n\tawait memGot('https://sindresorhus.com');\n\tawait memGot('https://sindresorhus.com');\n\n\tconsole.log(cache.stats);\n\t//=> {hits: 2, misses: 1}\n})();\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","readmeFilename":"readme.md","gitHead":"be5f6db8401486b597b280e40d18910690f6c737","bugs":{"url":"https://github.com/sindresorhus/mem/issues"},"homepage":"https://github.com/sindresorhus/mem#readme","_id":"mem@7.0.0-2","_nodeVersion":"14.4.0","_npmVersion":"6.14.5","dist":{"integrity":"sha512-Y5cusA/lEuuAC+a4JRsPsPDvCjqf1r3tdkGH7IZzSEsAoZb7vZod/xJQr2Cpybaud6QATYG+1ULce1hfu3iWMg==","shasum":"f88933ed3b7843ba1a8a89ac99c2910223711bfb","tarball":"http://registry-npm.ywwl.com/mem/download/mem-7.0.0-2.tgz","fileCount":5,"unpackedSize":14846,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfdZw2CRA9TVsSAnZWagAAZv8P/2sMEi7zX3fIyWCohQ7h\n+Q6CVyEWMY/JVMXf59RLrdz/YW5GbrJFlCbJoO2OcIJmgjl+QQvNd/59xgxh\nwn5ttEub9E9cdQB0WE1ekmnKHxvX5JU2MAid7bWE7ZyAsVm/x1MfytOTjKuH\nKJ6Vmocln1mG7pSnRmsOV6/tY9R7+N0FgtEz/fxKguQmDHdQP7lS2jvUxdyf\nFzM86OZ8yVw4g6ktDAEruw7LyGBcYjbEeCY5rfosFU06SCEBxaFH6SJv/v/G\nMxZpJ8bTQclrAOlkyKgqe7Iir5Q9nQ0MgTwvQ9NiyjyN5pruCZCkz1ImQ3K8\nLIjkKReKMmTl8PDzGXPNXo7EY0ado4Ts3x/9HAcYEMvdM+3+bKEg67ClSgHs\n/BheWi34AHlGI5WHt13kRzp0RlCqJPXDPBzo1reVj/xYe9hoxt1Qu3nWsAh3\nQy3SUybKkqJBA1mbl+yPxtieWp3mlM07ty+njpPWkX4H6VGrmVk8Ri8TkMe8\nC07O+NVZsesLj03ITa1HVZH15r39Nk4JwK+BRRUS5MJkCnQyFwtcaqFNNKqR\n3eRwwlYsjzJ0ulrlhprqSZd/cVAY96a3T9cCwNMH3VjFYleX5wsSX5kxEBmc\neUYOKFBrOsKJ5kkAJFGh+8IJyxS5gYL3h+LYnmL3b2aCyxlX7RgDmrj01CKI\nuwEL\r\n=l7Nf\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQDKa77IwalU5hrWH6KyoHHO1kJpv5DQS7sU9J9okQtD2AIhAP1L+soaXRlg6QHQhaiKXvebhwAFJa9vlx6RZA9zBZMa"}],"size":5032,"noattachment":false,"key":"/mem/-/mem-7.0.0-2.tgz"},"maintainers":[{"name":"sindresorhus","email":"sindresorhus@gmail.com"},{"name":"fregante","email":"opensource@bfred.it"}],"_npmUser":{"name":"fregante","email":"opensource@bfred.it"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/mem_7.0.0-2_1601543222172_0.814094441690246"},"_hasShrinkwrap":false,"publish_time":1601543222292,"_cnpm_publish_time":1601543222292,"dist-tags":{"latest":"10.0.0","next":"7.0.0-3"}}