From 3e371ec19dcb0030f3a069e9c81ae9084c1c4e8e Mon Sep 17 00:00:00 2001 From: gifvex Date: Fri, 18 Aug 2023 14:55:38 -0400 Subject: [PATCH] Add `JS::Object#to_a` --- ext/js/lib/js.rb | 9 +++++++++ .../ruby-wasm-wasi/test/unit/test_object.rb | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/ext/js/lib/js.rb b/ext/js/lib/js.rb index 37a850c966..eaf0d34cbb 100644 --- a/ext/js/lib/js.rb +++ b/ext/js/lib/js.rb @@ -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 diff --git a/packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb b/packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb index b25734bd30..b4a53929f7 100644 --- a/packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb +++ b/packages/npm-packages/ruby-wasm-wasi/test/unit/test_object.rb @@ -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