migrate to typescript

This commit is contained in:
Dainius Daukševičius
2020-10-17 21:56:54 +03:00
committed by Dainius Dauksevicius
parent c462323dd5
commit 08d27265fc
120 changed files with 5002 additions and 4711 deletions

View File

@@ -0,0 +1,43 @@
export function createMemoryCache(memoryFn: (...args: any[]) => void, cacheTimeMs: number) {
if (isNaN(cacheTimeMs)) cacheTimeMs = 0;
// holds the promise results
const cache = new Map();
// holds the promises that are not fulfilled
const promiseMemory = new Map();
return (...args: any[]) => {
// create cacheKey by joining arguments as string
const cacheKey = args.join('.');
// check if promising is already running
if (promiseMemory.has(cacheKey)) {
return promiseMemory.get(cacheKey);
} else {
// check if result is in cache
if (cache.has(cacheKey)) {
const cacheItem = cache.get(cacheKey);
const now = Date.now();
// check if cache is valid
if (!(cacheItem.cacheTime + cacheTimeMs < now)) {
return Promise.resolve(cacheItem.result);
}
}
// create new promise
const promise = new Promise(async (resolve) => {
resolve((await memoryFn(...args)));
});
// store promise reference until fulfilled
promiseMemory.set(cacheKey, promise);
return promise.then(result => {
// store promise result in cache
cache.set(cacheKey, {
result,
cacheTime: Date.now(),
});
// remove fulfilled promise from memory
promiseMemory.delete(cacheKey);
// return promise result
return result;
});
}
};
}