Skip to content

Commit

Permalink
Add Native::Array for array-like object wrapping
Browse files Browse the repository at this point in the history
  • Loading branch information
meh committed Sep 16, 2013
1 parent d5af5a5 commit 8d1443f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 9 deletions.
12 changes: 3 additions & 9 deletions corelib/kernel.rb
Expand Up @@ -64,19 +64,13 @@ def methods(all = true)
}
end

def Array(object, func = undefined, length = :length)
def Array(object, *args, &block)
%x{
if (object == null || object === nil) {
return [];
}
else if (#{native?(object)} && object[length] != null) {
var result = [];
for (var i = 0, length = object[length]; i < length; i++) {
result.push(func ? object[func](i) : object[i]);
}
return result;
else if (#{native?(object)}) {
return #{Native::Array.new(object, *args, &block).to_a};
}
else if (#{object.respond_to? :to_ary}) {
return #{object.to_ary};
Expand Down
61 changes: 61 additions & 0 deletions corelib/native.rb
Expand Up @@ -43,6 +43,67 @@ def to_n
end
end

class Array
include Base
include Enumerable

def initialize(native, options = {}, &block)
super(native)

@get = options[:get] || options[:access]
@set = options[:set] || options[:access]
@length = options[:length] || :length
@block = block

if `#@native[#@length] == null`

This comment has been minimized.

Copy link
@fntz

fntz Sep 16, 2013

Contributor

But you have already made a function for this (length). Why are you not using it?

This comment has been minimized.

Copy link
@meh

meh Sep 16, 2013

Author Member

Because I wrote this before writing the method 🐼

But I'd keep it that way since the check is native.

This comment has been minimized.

Copy link
@fntz

fntz Sep 16, 2013

Contributor

:)

raise ArgumentError, "no length found on the array-like object"
end
end

def each(&block)
return enum_for :each unless block

index = 0
length = self.length

while index < length
block.call(self[index])

index += 1
end

self
end

def [](index)
result = if @get
`#@native[#@get](#{index})`
else
`#@native[#{index}]`
end

unless index > length
if @block
@block.call(result)
else
Native(result)
end
end
end

def []=(index, value)
if @set
`#@native[#@set](#{index}, #{value})`
else
`#@native[#{index}] = #{value}`
end
end

def length
`#@native[#@length]`
end
end

def self.try_convert(value)
%x{
if (#{native?(value)}) {
Expand Down

0 comments on commit 8d1443f

Please sign in to comment.