Skip to content

Instantly share code, notes, and snippets.

@andrewkroh
Created October 3, 2024 18:58
Show Gist options
  • Save andrewkroh/19eccc0844bb935222914234c9510aa1 to your computer and use it in GitHub Desktop.
Save andrewkroh/19eccc0844bb935222914234c9510aa1 to your computer and use it in GitHub Desktop.
package goja_test
import (
"testing"
"github.com/dop251/goja"
)
type myMapStr map[string]interface{}
// toValue implements the goja [valueContainer] interface which allows custom
// types to implement their own [goja.Runtime] `ToValue()` behavior.
//
// [valueContainer]: https://github.com/dop251/goja/blob/fa6d1ed5e4b60afc19842edcbf806ddcd999524c/value.go#L97-L99
func (m myMapStr) toValue(r *goja.Runtime) goja.Value {
// Make mapStr back into a map[string]any so that ToValue can convert
// it into an object.
return r.ToValue(map[string]any(m))
}
func TestCustomMapStrToValue(t *testing.T) {
rt := goja.New()
rt.Set("m", myMapStr{
"event": myMapStr{
"type": "alert",
},
})
_, err := rt.RunString(`
if (m.event.type != "alert") {
throw "failed";
}
`)
if err != nil {
t.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment