MCPcopy
hub / github.com/webpack/webpack / cachedWithKey

Function cachedWithKey

lib/schemes/HttpUriPlugin.js:364–440  ·  view source on GitHub ↗
(fn, forceFn = fn)

Source from the content-addressed store, hash-verified

362 * @returns {FnWithKey<T, R> & { force: FnWithKey<T, R> }} cached function
363 */
364const cachedWithKey = (fn, forceFn = fn) => {
365 /**
366 * Defines the cache entry type used by this module.
367 * @template R
368 * @typedef {{ result?: R, error?: Error, callbacks?: FnWithKeyCallback<R>[], force?: true }} CacheEntry
369 */
370 /** @type {Map<T, CacheEntry<R>>} */
371 const cache = new Map();
372 /**
373 * Processes the provided arg.
374 * @param {T} arg arg
375 * @param {FnWithKeyCallback<R>} callback callback
376 * @returns {void}
377 */
378 const resultFn = (arg, callback) => {
379 const cacheEntry = cache.get(arg);
380 if (cacheEntry !== undefined) {
381 if (cacheEntry.result !== undefined) {
382 return callback(null, cacheEntry.result);
383 }
384 if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
385 if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
386 else cacheEntry.callbacks.push(callback);
387 return;
388 }
389 /** @type {CacheEntry<R>} */
390 const newCacheEntry = {
391 result: undefined,
392 error: undefined,
393 callbacks: undefined
394 };
395 cache.set(arg, newCacheEntry);
396 fn(arg, (err, result) => {
397 if (err) newCacheEntry.error = err;
398 else newCacheEntry.result = result;
399 const callbacks = newCacheEntry.callbacks;
400 newCacheEntry.callbacks = undefined;
401 callback(err, result);
402 if (callbacks !== undefined) for (const cb of callbacks) cb(err, result);
403 });
404 };
405 /**
406 * Processes the provided arg.
407 * @param {T} arg arg
408 * @param {FnWithKeyCallback<R>} callback callback
409 * @returns {void}
410 */
411 resultFn.force = (arg, callback) => {
412 const cacheEntry = cache.get(arg);
413 if (cacheEntry !== undefined && cacheEntry.force) {
414 if (cacheEntry.result !== undefined) {
415 return callback(null, cacheEntry.result);
416 }
417 if (cacheEntry.error !== undefined) return callback(cacheEntry.error);
418 if (cacheEntry.callbacks === undefined) cacheEntry.callbacks = [callback];
419 else cacheEntry.callbacks.push(callback);
420 return;
421 }

Callers 1

applyMethod · 0.85

Calls 4

callbackFunction · 0.50
getMethod · 0.45
pushMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected