Class: Native::Array

Inherits:
Object show all
Includes:
Enumerable, Native
Defined in:
opal/stdlib/native.rb

Instance Method Summary collapse

Methods included from Enumerable

#to_set

Methods included from Native

call, convert, included, is_a?, #to_n, try_convert

Constructor Details

#initialize(native, options = {}, &block) ⇒ Array

Returns a new instance of Array



249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'opal/stdlib/native.rb', line 249

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

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

  if `#{length} == null`
    raise ArgumentError, "no length found on the array-like object"
  end
end

Instance Method Details

#[](index) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'opal/stdlib/native.rb', line 279

def [](index)
  result = case index
    when String, Symbol
      @named ? `#@native[#@named](#{index})` : `#@native[#{index}]`

    when Integer
      @get ? `#@native[#@get](#{index})` : `#@native[#{index}]`
  end

  if result
    if @block
      @block.call(result)
    else
      Native(result)
    end
  end
end

#[]=(index, value) ⇒ Object



297
298
299
300
301
302
303
# File 'opal/stdlib/native.rb', line 297

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

#each(&block) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'opal/stdlib/native.rb', line 263

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

  %x{
    for (var i = 0, length = #{length}; i < length; i++) {
      var value = $opal.$yield1(block, #{self[`i`]});

      if (value === $breaker) {
        return $breaker.$v;
      }
    }
  }

  self
end

#inspectObject



329
330
331
# File 'opal/stdlib/native.rb', line 329

def inspect
  to_a.inspect
end

#last(count = nil) ⇒ Object



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'opal/stdlib/native.rb', line 305

def last(count = nil)
  if count
    index  = length - 1
    result = []

    while index >= 0
      result << self[index]
      index  -= 1
    end

    result
  else
    self[length - 1]
  end
end

#lengthObject



321
322
323
# File 'opal/stdlib/native.rb', line 321

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

#to_aryObject



325
326
327
# File 'opal/stdlib/native.rb', line 325

def to_ary
  self
end