2024-06-23 06:45:58 -06:00
|
|
|
package ucontainer
|
|
|
|
|
|
|
|
// Memo holds a cached value.
|
|
|
|
type Memo[T any] struct {
|
|
|
|
cache T
|
|
|
|
valid bool
|
|
|
|
update func () T
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewMemo creates a new Memo which will take its value from the specified
|
|
|
|
// update callback.
|
|
|
|
func NewMemo[T any] (update func () T) Memo[T] {
|
|
|
|
return Memo[T] {
|
|
|
|
update: update,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Value returns the Memo's value, updating it if the current cached value is
|
|
|
|
// invalid.
|
|
|
|
func (this *Memo[T]) Value () T {
|
|
|
|
if !this.valid {
|
|
|
|
this.cache = this.update()
|
|
|
|
}
|
|
|
|
return this.cache
|
|
|
|
}
|
|
|
|
|
|
|
|
// Invalidate marks the Memo's value as invalid, which will cause it to be
|
|
|
|
// updated the next time Value is called.
|
|
|
|
func (this *Memo[T]) Invalidate () {
|
2024-09-10 14:42:57 -06:00
|
|
|
var zero T
|
|
|
|
this.cache = zero
|
2024-06-23 06:45:58 -06:00
|
|
|
this.valid = false
|
|
|
|
}
|
|
|
|
|