Last active
March 1, 2024 13:00
-
-
Save fsubal/cd0f9e2a162cff29ae1028bd2b8ad18b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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