Skip to content

Commit

Permalink
Throw on clear(fn) if fn’s cache can't be cleared (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Oct 7, 2020
1 parent 837e393 commit e7c8893
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
12 changes: 7 additions & 5 deletions index.ts
Expand Up @@ -141,12 +141,14 @@ Clear all cached data of a memoized function.
@param fn - Memoized function.
*/
mem.clear = (fn: (...arguments_: any[]) => any): void => {
if (!cacheStore.has(fn)) {
throw new Error('Can\'t clear a function that was not memoized!');
const cache = cacheStore.get(fn);
if (!cache) {
throw new TypeError('Can\'t clear a function that was not memoized!');
}

const cache = cacheStore.get(fn);
if (typeof cache.clear === 'function') {
cache.clear();
if (typeof cache.clear !== 'function') {
throw new TypeError('The cache Map can\'t be cleared!');
}

cache.clear();
};
17 changes: 16 additions & 1 deletion test.js
Expand Up @@ -198,6 +198,21 @@ test('mem.clear() throws when called with a plain function', t => {
t.throws(() => {
mem.clear(() => {});
}, {
message: 'Can\'t clear a function that was not memoized!'
message: 'Can\'t clear a function that was not memoized!',
instanceOf: TypeError
});
});

test('mem.clear() throws when called on an unclearable cache', t => {
const fixture = () => 1;
const memoized = mem(fixture, {
cache: new WeakMap()
});

t.throws(() => {
mem.clear(memoized);
}, {
message: 'The cache Map can\'t be cleared!',
instanceOf: TypeError
});
});

0 comments on commit e7c8893

Please sign in to comment.