-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(memoizecapped): adding specialized memoize function version
clears the memoize function's cache when it exceeds max size
- Loading branch information
1 parent
c55032d
commit 4e88c35
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |