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



447
448
449
450
451
452
453
454
455
456
457
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
# File 'opal/stdlib/native.rb', line 447

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

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

          if (key.$$is_string) {
            map = smap;
            khash = key;
          } else {
            map = _map;
            khash = key.$hash();
          }

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

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

    return self;
  }
end

Instance Method Details

#to_jsonObject



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'opal/stdlib/json.rb', line 137

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

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

      if (key.$$is_string) {
        map = smap;
        khash = key;
      } else {
        map = _map;
        khash = key.$hash();
      }

      inspect.push(#{`key`.to_s.to_json} + ':' + #{`map[khash]`.to_json});
    }

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

#to_nObject



489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'opal/stdlib/native.rb', line 489

def to_n
  %x{
    var result = {},
        keys   = self.keys,
        _map   = self.map,
        smap   = self.smap,
        map, khash, value, key;

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

      if (key.$$is_string) {
        map = smap;
        khash = key;
      } else {
        map = _map;
        khash = key.$hash();
      }

      value = map[khash];

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

    return result;
  }
end