zntg/ui/cache.go

39 lines
929 B
Go

package ui
type CacheHashFn func(interface{}) string
type CacheHashContextFn func(Context) string
func (c CacheHashContextFn) Fn() CacheHashFn {
return func(state interface{}) string { return c(state.(Context)) }
}
type CacheUpdateFn func(interface{}) interface{}
type CacheUpdateContextFn func(Context) interface{}
func (c CacheUpdateContextFn) Fn() CacheUpdateFn {
return func(state interface{}) interface{} { return c(state.(Context)) }
}
type Cache struct {
value interface{}
hash string
updateFn CacheUpdateFn
hashFn CacheHashFn
}
func NewCache(update CacheUpdateFn, hash CacheHashFn) *Cache {
return &Cache{updateFn: update, hashFn: hash}
}
func NewCacheContext(update CacheUpdateContextFn, hash CacheHashContextFn) *Cache {
return NewCache(update.Fn(), hash.Fn())
}
func (c *Cache) Get(state interface{}) interface{} {
if c.hashFn(state) != c.hash {
c.value = c.updateFn(state)
}
return c.value
}