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_json, #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



268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'opal/stdlib/native.rb', line 268

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



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'opal/stdlib/native.rb', line 298

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



316
317
318
319
320
321
322
# File 'opal/stdlib/native.rb', line 316

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

#each(&block) ⇒ Object



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

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



346
347
348
# File 'opal/stdlib/native.rb', line 346

def inspect
  to_a.inspect
end

#last(count = nil) ⇒ Object



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'opal/stdlib/native.rb', line 324

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



340
341
342
# File 'opal/stdlib/native.rb', line 340

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