MCPcopy Index your code
hub / github.com/Xyntopia/taskyon / asyncTimeLruCache

Function asyncTimeLruCache

src/modules/utils.ts:127–174  ·  view source on GitHub ↗
(
  size: number,
  maxAge: number, // Maximum age in milliseconds
  ignoreIndices: number[] = []
)

Source from the content-addressed store, hash-verified

125};
126
127export function asyncTimeLruCache<ReturnType>(
128 size: number,
129 maxAge: number, // Maximum age in milliseconds
130 ignoreIndices: number[] = []
131): (fn: AnyFunction<Promise<ReturnType>>) => AnyFunction<Promise<ReturnType>> {
132 // The cache for storing function call results.
133 const cache = new Map<string, asyncCacheEntry<ReturnType>>();
134
135 return (
136 fn: AnyFunction<Promise<ReturnType>>
137 ): AnyFunction<Promise<ReturnType>> => {
138 return async function (...args: unknown[]): Promise<ReturnType> {
139 // Generate a cache key, ignoring specified arguments.
140 const keyArgs = args.filter((_, index) => !ignoreIndices.includes(index));
141 const key = JSON.stringify(keyArgs);
142
143 const now = Date.now();
144
145 // Check for a cache hit.
146 if (cache.has(key)) {
147 const entry = cache.get(key) as asyncCacheEntry<ReturnType>;
148 const age = now - entry.timestamp;
149
150 if (age <= maxAge) {
151 //console.log('Cache hit:', key);
152 return entry.value;
153 } else {
154 //console.log('Cache expired:', key);
155 cache.delete(key); // Remove the expired entry.
156 }
157 }
158
159 // Call the original function and cache the result.
160 const result = fn(...args);
161 cache.set(key, { value: result, timestamp: now });
162
163 // Check the cache size and evict the least recently used item if necessary.
164 if (cache.size > size) {
165 const oldestKey = Array.from(cache.keys())[0];
166 cache.delete(oldestKey);
167 console.log('Evicted:', oldestKey);
168 }
169
170 // Return the result.
171 return result;
172 };
173 };
174}
175
176export function asyncLruCache<ReturnType>(
177 size: number,

Callers 1

chat.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected