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



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

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



129
130
131
132
133
134
135
136
137
138
139
140
# File 'opal/stdlib/json.rb', line 129

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



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'opal/stdlib/native.rb', line 490

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