diff --git a/index.js b/index.js index 493090e..46c2d9e 100644 --- a/index.js +++ b/index.js @@ -4,15 +4,11 @@ const mapAgeCleaner = require('map-age-cleaner'); const cacheStore = new WeakMap(); -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; - +const mem = (fn, { + cacheKey = ([firstArgument]) => firstArgument, + cache = new Map(), + maxAge +} = {}) => { if (typeof maxAge === 'number') { mapAgeCleaner(cache); } @@ -20,18 +16,13 @@ const mem = (fn, options = {}) => { const memoized = function (...arguments_) { const key = cacheKey(arguments_); - // 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; + if (cache.has(key)) { + return cache.get(key).data; } const cacheItem = fn.apply(this, arguments_); - bestCache.set(key, { + cache.set(key, { data: cacheItem, maxAge: maxAge ? Date.now() + maxAge : Infinity }); diff --git a/readme.md b/readme.md index eb1b597..824ec47 100644 --- a/readme.md +++ b/readme.md @@ -190,9 +190,9 @@ Refer to the [caching strategies](#caching-strategy) section for more informatio ##### cache Type: `object`\ -Default: `new Map()`, but it also intelligently uses `new WeakMap()` whenevever possible +Default: `new Map()` -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. +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. Refer to the [caching strategies](#caching-strategy) section for more information.