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



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

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



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'opal/stdlib/native.rb', line 309

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



327
328
329
330
331
332
333
# File 'opal/stdlib/native.rb', line 327

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

#each(&block) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'opal/stdlib/native.rb', line 293

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



357
358
359
# File 'opal/stdlib/native.rb', line 357

def inspect
  to_a.inspect
end

#last(count = nil) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'opal/stdlib/native.rb', line 335

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



351
352
353
# File 'opal/stdlib/native.rb', line 351

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