strings.go raw

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