Skip to content

Commit 3e371ec

Browse files
gifvexkateinoigakukun
authored andcommitted
Add JS::Object#to_a
1 parent 097b7ca commit 3e371ec

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

ext/js/lib/js.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,15 @@ def new(*args)
138138
JS.global[:Reflect].construct(self, args.to_js)
139139
end
140140

141+
# Converts +self+ to an Array:
142+
#
143+
# JS.eval("return [1, 2, 3]").to_a.map(&:to_i) # => [1, 2, 3]
144+
# JS.global[:document].querySelectorAll("p").to_a # => [[object HTMLParagraphElement], ...
145+
def to_a
146+
as_array = JS.global[:Array].from(self)
147+
Array.new(as_array[:length].to_i) { as_array[_1] }
148+
end
149+
141150
# Provide a shorthand form for JS::Object#call
142151
#
143152
# This method basically calls the JavaScript method with the same

packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,17 @@ class CustomClass {
245245
assert_equal "hello", JS.global[:CustomClass].new(js_object)[:option1].to_s
246246
end
247247

248+
def test_to_a
249+
assert_equal [1, 2, 3], JS.eval("return [1, 2, 3];").to_a.map(&:to_i)
250+
assert_equal %w[f o o], JS.eval("return 'foo';").to_a.map(&:to_s)
251+
252+
set = JS.eval("return new Set(['foo', 'bar', 'baz', 'foo']);").to_a
253+
assert_equal %w[foo bar baz], set.map(&:to_s)
254+
255+
map = JS.eval("return new Map([[1, 2], [2, 4], [4, 8]]);").to_a
256+
assert_equal ({ 1 => 2, 2 => 4, 4 => 8 }), map.to_h { _1.to_a.map(&:to_i) }
257+
end
258+
248259
def test_method_missing
249260
assert_equal "42", JS.eval("return 42;").toString.to_s
250261
assert_equal "o", JS.eval("return 'hello';").charAt(4).to_s

0 commit comments

Comments
 (0)