1 # mem [![Build Status](https://travis-ci.org/sindresorhus/mem.svg?branch=master)](https://travis-ci.org/sindresorhus/mem)
3 > [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
5 Memory is automatically released when an item expires.
18 const mem = require('mem');
21 const counter = () => ++i;
22 const memoized = mem(counter);
27 // Cached as it's the same arguments
31 // Not cached anymore as the arguments changed
39 ##### Works fine with promise returning functions
42 const mem = require('mem');
45 const counter = async () => ++i;
46 const memoized = mem(counter);
49 console.log(await memoized());
52 // The return value didn't increase as it's cached
53 console.log(await memoized());
59 const mem = require('mem');
60 const got = require('got');
61 const delay = require('delay');
63 const memGot = mem(got, {maxAge: 1000});
66 await memGot('sindresorhus.com');
68 // This call is cached
69 await memGot('sindresorhus.com');
73 // This call is not cached as the cache has expired
74 await memGot('sindresorhus.com');
81 ### mem(fn, [options])
87 Function to be memoized.
98 Milliseconds until the cache expires.
104 Determines the cache key for storing the result based on the function arguments. By default, if there's only one argument and it's a [primitive](https://developer.mozilla.org/en-US/docs/Glossary/Primitive), it's used directly as a key, otherwise it's all the function arguments JSON stringified as an array.
106 You could for example change it to only cache on the first argument `x => JSON.stringify(x)`.
113 Use 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.
115 ##### cachePromiseRejection
120 Cache rejected promises.
124 Clear all cached data of a memoized function.
137 If 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.
142 const mem = require('mem');
143 const StatsMap = require('stats-map');
144 const got = require('got');
146 const cache = new StatsMap();
147 const memGot = mem(got, {cache});
150 await memGot('sindresorhus.com');
151 await memGot('sindresorhus.com');
152 await memGot('sindresorhus.com');
154 console.log(cache.stats);
155 //=> {hits: 2, misses: 1}
162 - [p-memoize](https://github.com/sindresorhus/p-memoize) - Memoize promise-returning & async functions
167 MIT © [Sindre Sorhus](https://sindresorhus.com)