Skip to content

Commit

Permalink
Revert "Automatically use WeakMap when possible" (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante authored May 16, 2020
1 parent 410ec9f commit 3ffde5d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 19 deletions.
25 changes: 8 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,25 @@ 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);
}

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
});
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down

0 comments on commit 3ffde5d

Please sign in to comment.