Skip to content

Commit

Permalink
Add JS::Object#to_a
Browse files Browse the repository at this point in the history
  • Loading branch information
gifvex authored and kateinoigakukun committed Oct 29, 2023
1 parent 097b7ca commit 3e371ec
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
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

0 comments on commit 3e371ec

Please sign in to comment.