Skip to content

Commit e8bb86c

Browse files
authored
Automatically use WeakMap when possible (#56)
1 parent 9d2d607 commit e8bb86c

File tree

2 files changed

+19
-10
lines changed

2 files changed

+19
-10
lines changed

index.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,34 @@ const mapAgeCleaner = require('map-age-cleaner');
44

55
const cacheStore = new WeakMap();
66

7-
const mem = (fn, {
8-
cacheKey = ([firstArgument]) => firstArgument,
9-
cache = new Map(),
10-
maxAge
11-
} = {}) => {
7+
const mem = (fn, options = {}) => {
8+
// Automatically use WeakMap unless the user provided their own cache
9+
const weakCache = options.cache || new WeakMap();
10+
const {
11+
cacheKey = ([firstArgument]) => firstArgument,
12+
cache = new Map(),
13+
maxAge
14+
} = options;
15+
1216
if (typeof maxAge === 'number') {
1317
mapAgeCleaner(cache);
1418
}
1519

1620
const memoized = function (...arguments_) {
1721
const key = cacheKey(arguments_);
1822

19-
if (cache.has(key)) {
20-
return cache.get(key).data;
23+
// Prefer WeakMap if the key allows it
24+
const bestCache = key && (typeof key === 'object' || typeof key === 'function') ?
25+
weakCache :
26+
cache;
27+
28+
if (bestCache.has(key)) {
29+
return bestCache.get(key).data;
2130
}
2231

2332
const cacheItem = fn.apply(this, arguments_);
2433

25-
cache.set(key, {
34+
bestCache.set(key, {
2635
data: cacheItem,
2736
maxAge: maxAge ? Date.now() + maxAge : Infinity
2837
});

readme.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,9 +193,9 @@ Refer to the [caching strategies](#caching-strategy) section for more informatio
193193
##### cache
194194

195195
Type: `object`\
196-
Default: `new Map()`
196+
Default: `new Map()`, but it also intelligently uses `new WeakMap()` whenevever possible
197197

198-
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.
198+
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 [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
199199

200200
Refer to the [caching strategies](#caching-strategy) section for more information.
201201

0 commit comments

Comments
 (0)