Skip to content

Commit

Permalink
feat(memoizecapped): adding specialized memoize function version
Browse files Browse the repository at this point in the history
clears the memoize function's cache when it exceeds max size
  • Loading branch information
roggervalf committed Apr 30, 2020
1 parent c55032d commit 4e88c35
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/memoizeCapped.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { memoizeCapped, MAX_MEMOIZE_SIZE } from './memoizeCapped';

describe('memoizeCapped', () => {
it('should enforce a max cache size of `MAX_MEMOIZE_SIZE`', () => {
function identity<T>(value: T): T {
return value;
}
const memoized = memoizeCapped(identity);
const cache = memoized.cache;

Array.from(Array(MAX_MEMOIZE_SIZE).keys()).forEach((value, index) => {
memoized(index);
});
expect(cache.size).toEqual(MAX_MEMOIZE_SIZE);
memoized(MAX_MEMOIZE_SIZE);
expect(cache.size).toEqual(1);
});
});
24 changes: 24 additions & 0 deletions src/memoizeCapped.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { memoize } from './memoize';
import { MemoizeInterface } from './types';

/** Used as the maximum memoize cache size. */
export const MAX_MEMOIZE_SIZE = 500;

/**
* A specialized version of `memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
export function memoizeCapped(func: Function): MemoizeInterface {
const result = memoize(func, (key: any) => {
const { cache } = result;
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});

return result;
}

0 comments on commit 4e88c35

Please sign in to comment.