first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
"use strict";
const cacheStore = new WeakMap();
// eslint-disable-next-line jsdoc/no-restricted-syntax
/**
* @template T
* @typedef {(...args: any) => T} FunctionReturning
*/
/**
* @template T
* @param {FunctionReturning<T>} fn memorized function
* @param {({ cache?: Map<string, { data: T }> } | undefined)=} cache cache
* @param {((value: T) => T)=} callback callback
* @returns {FunctionReturning<T>} new function
*/
function memorize(fn, {
cache = new Map()
} = {}, callback = undefined) {
// eslint-disable-next-line jsdoc/no-restricted-syntax
/**
* @param {any} arguments_ args
* @returns {any} result
*/
const memoized = (...arguments_) => {
const [key] = arguments_;
const cacheItem = cache.get(key);
if (cacheItem) {
return cacheItem.data;
}
// @ts-expect-error
let result = fn.apply(this, arguments_);
if (callback) {
result = callback(result);
}
cache.set(key, {
data: result
});
return result;
};
cacheStore.set(memoized, cache);
return memoized;
}
module.exports = memorize;