this repo has no description
at main 26 lines 784 B view raw
1// eslint-disable-next-line import/prefer-default-export 2export function memoize<T extends unknown[], S>( 3 fn: (...args: T) => S, 4 hashFn: (...args: unknown[]) => string = JSON.stringify, 5 entryLimit = 5, 6): (...args: T) => S { 7 const cache: Map<string, S> = new Map(); 8 9 return (...args: T) => { 10 const value = hashFn(args); 11 if (cache.has(value)) { 12 return cache.get(value); 13 } 14 15 const returnedValue: S = fn.apply(this, args); 16 17 if (cache.size >= entryLimit) { 18 const iterator = cache.keys(); 19 const firstValue = iterator.next().value; 20 // remove oldest value 21 cache.delete(firstValue); 22 } 23 cache.set(value, returnedValue); 24 return returnedValue; 25 }; 26}