Skip to content

Commit

Permalink
Automatically use WeakMap when possible (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored Apr 12, 2020
1 parent 9d2d607 commit e8bb86c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
25 changes: 17 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,34 @@ const mapAgeCleaner = require('map-age-cleaner');

const cacheStore = new WeakMap();

const mem = (fn, {
cacheKey = ([firstArgument]) => firstArgument,
cache = new Map(),
maxAge
} = {}) => {
const mem = (fn, options = {}) => {
// Automatically use WeakMap unless the user provided their own cache
const weakCache = options.cache || new WeakMap();
const {
cacheKey = ([firstArgument]) => firstArgument,
cache = new Map(),
maxAge
} = options;

if (typeof maxAge === 'number') {
mapAgeCleaner(cache);
}

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

if (cache.has(key)) {
return cache.get(key).data;
// Prefer WeakMap if the key allows it
const bestCache = key && (typeof key === 'object' || typeof key === 'function') ?
weakCache :
cache;

if (bestCache.has(key)) {
return bestCache.get(key).data;
}

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

cache.set(key, {
bestCache.set(key, {
data: cacheItem,
maxAge: maxAge ? Date.now() + maxAge : Infinity
});
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,9 @@ Refer to the [caching strategies](#caching-strategy) section for more informatio
##### cache

Type: `object`\
Default: `new Map()`
Default: `new Map()`, but it also intelligently uses `new WeakMap()` whenevever possible

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.
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.

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

Expand Down

0 comments on commit e8bb86c

Please sign in to comment.