Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active March 1, 2024 13:00
Show Gist options
  • Save fsubal/cd0f9e2a162cff29ae1028bd2b8ad18b to your computer and use it in GitHub Desktop.
Save fsubal/cd0f9e2a162cff29ae1028bd2b8ad18b to your computer and use it in GitHub Desktop.
export function memo<T extends (...args: any[]) => any>(fn: T): T {
const call = Object.assign(fn, { cache: null as ReturnType<T> | null })
return ((...args: Parameters<T>) => call.cache ??= call(...args)) as T
}
export class Foo {
bar = memo(() => 1)
}
export type Mutable<T> = {
-readonly [K in keyof T]: T[K]
}
export class Foo {
get bar() {
return cache(this, 'bar', () => 1)
}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get#smart_self-overwriting_lazy_getters
*/
function cache<T, K extends keyof T, V extends T[K]>(self: T, prop: K, value: () => V) {
delete self[prop]
return self[prop] = value()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment