Skip to content

Instantly share code, notes, and snippets.

@ScriptRaccoon
Created June 13, 2023 22:14
Show Gist options
  • Select an option

  • Save ScriptRaccoon/70e008ca5ceb9885a088c5cc4c9bd657 to your computer and use it in GitHub Desktop.

Select an option

Save ScriptRaccoon/70e008ca5ceb9885a088c5cc4c9bd657 to your computer and use it in GitHub Desktop.
Cache decorator function
/**
* This is a general decorator function which caches the
* return value of a function for a specified amount of time.
* This can be used to save responses from API requests for example.
* @param fun any function (without arguments)
* @param duration caching duration in milliseconds
* @returns the function return value when the cache is empty or old, or the cache value
*/
export function cached<T>(fun: () => T, duration: number) {
let date: Date | null = null;
let cache: T | null = null;
return function (): T {
if (
cache &&
date &&
new Date().getTime() - date.getTime() <= duration
) {
return cache;
}
const result = fun();
cache = result;
date = new Date();
return result;
};
}
// Example:
const one_day = 24 * 60 * 60 * 1000;
const cached_api_response = cached(async () => {
return await fetch(process.env.API_URL);
}, one_day);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment