Skip to content

Add JS::Object#to_a #270

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

Merged
merged 1 commit into from
Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions ext/js/lib/js.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,15 @@ def new(*args)
JS.global[:Reflect].construct(self, args.to_js)
end

# Converts +self+ to an Array:
#
# JS.eval("return [1, 2, 3]").to_a.map(&:to_i) # => [1, 2, 3]
# JS.global[:document].querySelectorAll("p").to_a # => [[object HTMLParagraphElement], ...
def to_a
as_array = JS.global[:Array].from(self)
Array.new(as_array[:length].to_i) { as_array[_1] }
end

# Provide a shorthand form for JS::Object#call
#
# This method basically calls the JavaScript method with the same
Expand Down
11 changes: 11 additions & 0 deletions packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,17 @@ class CustomClass {
assert_equal "hello", JS.global[:CustomClass].new(js_object)[:option1].to_s
end

def test_to_a
assert_equal [1, 2, 3], JS.eval("return [1, 2, 3];").to_a.map(&:to_i)
assert_equal %w[f o o], JS.eval("return 'foo';").to_a.map(&:to_s)

set = JS.eval("return new Set(['foo', 'bar', 'baz', 'foo']);").to_a
assert_equal %w[foo bar baz], set.map(&:to_s)

map = JS.eval("return new Map([[1, 2], [2, 4], [4, 8]]);").to_a
assert_equal ({ 1 => 2, 2 => 4, 4 => 8 }), map.to_h { _1.to_a.map(&:to_i) }
end

def test_method_missing
assert_equal "42", JS.eval("return 42;").toString.to_s
assert_equal "o", JS.eval("return 'hello';").charAt(4).to_s
Expand Down