strings.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //go:build js && wasm
  2. // +build js,wasm
  3. package jscache
  4. import (
  5. "github.com/hack-pad/safejs"
  6. )
  7. var (
  8. jsReflectGet safejs.Value
  9. )
  10. func init() {
  11. jsReflect, err := safejs.Global().Get("Reflect")
  12. if err != nil {
  13. panic(err)
  14. }
  15. jsReflectGet, err = jsReflect.Get("get")
  16. if err != nil {
  17. panic(err)
  18. }
  19. }
  20. // Strings caches encoding strings as safejs.Value's.
  21. // String encoding today is quite CPU intensive, so caching commonly used strings helps with performance.
  22. type Strings struct {
  23. cacher
  24. }
  25. // Value retrieves the safejs.Value for the given string
  26. func (c *Strings) Value(s string) safejs.Value {
  27. return c.value(s, identityStringGetter{s}.value)
  28. }
  29. // GetProperty retrieves the given object's property, using a cached string value if available. Saves on the performance cost of 2 round trips to JS.
  30. func (c *Strings) GetProperty(obj safejs.Value, key string) (safejs.Value, error) {
  31. jsKey := c.Value(key)
  32. return jsReflectGet.Invoke(obj, jsKey)
  33. }
  34. type identityStringGetter struct {
  35. s string
  36. }
  37. func (i identityStringGetter) value() safejs.Value {
  38. value, err := safejs.ValueOf(i.s)
  39. if err != nil {
  40. panic(err)
  41. }
  42. return value
  43. }