Skip to content

Instantly share code, notes, and snippets.

@ViliamKopecky
Created March 10, 2022 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ViliamKopecky/bdd62269f31fcd4db64fc8ec84cb0fcb to your computer and use it in GitHub Desktop.
Save ViliamKopecky/bdd62269f31fcd4db64fc8ec84cb0fcb to your computer and use it in GitHub Desktop.
minimemo.ts
export async function memo<Value>(
key: string,
loader: () => Value | Promise<Value>
) {
const g = global as unknown as {
memory: Record<string, { value: Value | Promise<Value>; timestamp: number }>
}
const memory = g.memory ?? {}
g.memory = memory
const now = new Date().getTime()
const old = now - 30 * 1000
if (g.memory[key]?.timestamp > old) {
return g.memory[key].value as Value
}
const value = loader()
g.memory[key] = { value, timestamp: new Date().getTime() }
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment