Creating a getter cache can help optimize performance by storing and reusing the value rather than recalculating it each time. I am seeking the most efficient method to implement a getter cache without relying on decorators. While there are libraries that offer decorator solutions such as @cache
, I prefer a more succinct approach with minimal typing.
Here is an example:
type NoUndefined<T> = T extends undefined ? never : T;
function isNoUndefined <T> (value: T): value is NoUndefined<T> {
return typeof value !== 'undefined'
}
function handleGetter <T>(value:T, operation: () => NoUndefined<T>): NoUndefined<T> {
if (isNoUndefined(value)) return value;
return operation()
}
class CalendarDate extends Date {
#day: number | undefined = undefined
get day () {
return this.#day = handleGetter(this.#day, () => {
console.log('runs once')
return this.getDate()
})
}
}
const c = new CalendarDate()
c.day
c.day
c.day
c.day