diff options
| author | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
|---|---|---|
| committer | rxliuli <rxliuli@gmail.com> | 2025-11-04 05:03:50 +0800 |
| commit | bce557cc2dc767628bed6aac87301a1be7c5431b (patch) | |
| tree | b51a051228d01fe3306cd7626d4a96768aadb944 /shared/components/src/utils/memoize.ts | |
init commit
Diffstat (limited to 'shared/components/src/utils/memoize.ts')
| -rw-r--r-- | shared/components/src/utils/memoize.ts | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/shared/components/src/utils/memoize.ts b/shared/components/src/utils/memoize.ts new file mode 100644 index 0000000..a5e07ef --- /dev/null +++ b/shared/components/src/utils/memoize.ts @@ -0,0 +1,26 @@ +// eslint-disable-next-line import/prefer-default-export +export function memoize<T extends unknown[], S>( + fn: (...args: T) => S, + hashFn: (...args: unknown[]) => string = JSON.stringify, + entryLimit = 5, +): (...args: T) => S { + const cache: Map<string, S> = new Map(); + + return (...args: T) => { + const value = hashFn(args); + if (cache.has(value)) { + return cache.get(value); + } + + const returnedValue: S = fn.apply(this, args); + + if (cache.size >= entryLimit) { + const iterator = cache.keys(); + const firstValue = iterator.next().value; + // remove oldest value + cache.delete(firstValue); + } + cache.set(value, returnedValue); + return returnedValue; + }; +} |
