Skip to content

Commit 8d1443f

Browse files
committed
Add Native::Array for array-like object wrapping
1 parent d5af5a5 commit 8d1443f

File tree

2 files changed

+64
-9
lines changed

2 files changed

+64
-9
lines changed

corelib/kernel.rb

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,19 +64,13 @@ def methods(all = true)
6464
}
6565
end
6666

67-
def Array(object, func = undefined, length = :length)
67+
def Array(object, *args, &block)
6868
%x{
6969
if (object == null || object === nil) {
7070
return [];
7171
}
72-
else if (#{native?(object)} && object[length] != null) {
73-
var result = [];
74-
75-
for (var i = 0, length = object[length]; i < length; i++) {
76-
result.push(func ? object[func](i) : object[i]);
77-
}
78-
79-
return result;
72+
else if (#{native?(object)}) {
73+
return #{Native::Array.new(object, *args, &block).to_a};
8074
}
8175
else if (#{object.respond_to? :to_ary}) {
8276
return #{object.to_ary};

corelib/native.rb

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,67 @@ def to_n
4343
end
4444
end
4545

46+
class Array
47+
include Base
48+
include Enumerable
49+
50+
def initialize(native, options = {}, &block)
51+
super(native)
52+
53+
@get = options[:get] || options[:access]
54+
@set = options[:set] || options[:access]
55+
@length = options[:length] || :length
56+
@block = block
57+
58+
if `#@native[#@length] == null`
59+
raise ArgumentError, "no length found on the array-like object"
60+
end
61+
end
62+
63+
def each(&block)
64+
return enum_for :each unless block
65+
66+
index = 0
67+
length = self.length
68+
69+
while index < length
70+
block.call(self[index])
71+
72+
index += 1
73+
end
74+
75+
self
76+
end
77+
78+
def [](index)
79+
result = if @get
80+
`#@native[#@get](#{index})`
81+
else
82+
`#@native[#{index}]`
83+
end
84+
85+
unless index > length
86+
if @block
87+
@block.call(result)
88+
else
89+
Native(result)
90+
end
91+
end
92+
end
93+
94+
def []=(index, value)
95+
if @set
96+
`#@native[#@set](#{index}, #{value})`
97+
else
98+
`#@native[#{index}] = #{value}`
99+
end
100+
end
101+
102+
def length
103+
`#@native[#@length]`
104+
end
105+
end
106+
46107
def self.try_convert(value)
47108
%x{
48109
if (#{native?(value)}) {

0 commit comments

Comments
 (0)