Class: Hash

Inherits:
Object show all
Defined in:
opal/stdlib/json.rb,
opal/stdlib/native.rb

Instance Method Summary collapse

Constructor Details

#initialize(defaults = undefined, &block) ⇒ Hash

Returns a new instance of Hash



430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
# File 'opal/stdlib/native.rb', line 430

def initialize(defaults = undefined, &block)
  %x{
    if (defaults != null) {
      if (defaults.constructor === Object) {
        var map  = self.map,
            keys = self.keys;

        for (var key in defaults) {
          var value = defaults[key];

          if (value && value.constructor === Object) {
            map[key] = #{Hash.new(`value`)};
          }
          else {
            map[key] = #{Native(`defaults[key]`)};
          }

          keys.push(key);
        }
      }
      else {
        self.none = defaults;
      }
    }
    else if (block !== nil) {
      self.proc = block;
    }

    return self;
  }
end

Instance Method Details

#to_jsonObject



140
141
142
143
144
145
146
147
148
149
150
151
# File 'opal/stdlib/json.rb', line 140

def to_json
  %x{
    var inspect = [], keys = self.keys, map = self.map;

    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      inspect.push(#{`key`.to_s.to_json} + ':' + #{`map[key]`.to_json});
    }

    return '{' + inspect.join(', ') + '}';
  }
end

#to_nObject



462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# File 'opal/stdlib/native.rb', line 462

def to_n
  %x{
    var result = {},
        keys   = self.keys,
        map    = self.map,
        bucket,
        value;

    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i],
          obj = map[key];

      if (#{`obj`.respond_to? :to_n}) {
        result[key] = #{`obj`.to_n};
      }
      else {
        result[key] = obj;
      }
    }

    return result;
  }
end