Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't export sets? #336

Closed
jmdacruz opened this issue Nov 5, 2021 · 1 comment
Closed

Can't export sets? #336

jmdacruz opened this issue Nov 5, 2021 · 1 comment
Labels

Comments

@jmdacruz
Copy link

jmdacruz commented Nov 5, 2021

I'm using the following function to try and interact with sets in JavaScript:

func TestSets(t *testing.T) {
	runtime := goja.New()

	v, err := runtime.RunString(`var s = new Set([5]);s`)
        // v, err := runtime.RunString(`var s = new Set([5]);s.has(5)`)
	if err != nil {
		panic(err)
	}
	exported := v.Export()
	fmt.Println(exported)
}

While exported is of type map[string]interface{} (looks like the base object export method is used here), I'm getting an empty map when I would expect one that has the element 5. If I change the JavaScript code with the one that is commented out (testing to see if the set contains an element using the has method), then exported is a boolean (with value "true" in this case). This seems to indicate that the code is doing what it is supposed to do, but exporting the set yields an empty map. What am I doing wrong? Is exporting of the set type supported?

@dop251
Copy link
Owner

dop251 commented Nov 7, 2021

I'm not sure there is a good solution here. There is no set type in Go, but that's ok, we could export into map[interface{}]struct{} for example. But, while this would work for primitives, it wouldn't for objects, because they are unhashable (so you'll get a runtime panic if you try to use one as a key) and even if they were, exporting an Object produces an independent copy so equality match wouldn't work.

Depending on what you're going to do with the exported value, you could either interact with un-exported *Object representing the Set, like this:

	const SCRIPT = `
	const s = new Set();
	s.add(1);
	s;
	`
	vm := New()
	s, err := vm.RunString(SCRIPT)
	if err != nil {
		panic(err)
	}
	if setObj, ok := s.(*Object); ok {
		if has, ok := AssertFunction(setObj.Get("has")); ok {
			flag, err := has(setObj, vm.ToValue(1))
			if err != nil {
				panic(err)
			}
			t.Log(flag) // prints 'true'
		}
	}

Or convert it into something that can be exported (like an array) in JS code.

@dop251 dop251 added the question label Jan 6, 2022
@dop251 dop251 closed this as completed Jan 6, 2022
@dop251 dop251 mentioned this issue Jan 15, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants