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



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'opal/stdlib/native.rb', line 527

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

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

        if (value && value.constructor === Object) {
          smap[key] = #{Hash.new(`value`)};
        } else if (value && value.$$is_array) {
          value = value.map(function(item) {
            if (item && item.constructor === Object) {
              return #{Hash.new(`item`)};
            }

            return item;
          });
          smap[key] = value
        } else {
          smap[key] = #{Native(`value`)};
        }

        keys.push(key);
      }

      return self;
    }

    return #{_initialize(defaults, &block)};
  }
end

Instance Method Details

#_initializeObject



525
# File 'opal/stdlib/native.rb', line 525

alias_method :_initialize, :initialize

#to_jsonObject



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 142

def to_json
  %x{
    var result = [];

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

      if (key.$$is_string) {
        value = self.$$smap[key];
      } else {
        value = key.value;
        key = key.key;
      }

      result.push(#{`key`.to_s.to_json} + ':' + #{`value`.to_json});
    }

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

#to_nObject

Public: Returns a JavaScript object with the same keys but calling #to_n on all values.



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'opal/stdlib/native.rb', line 564

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

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

      if (key.$$is_string) {
        value = smap[key];
      } else {
        key = key.key;
        value = key.value;
      }

      result[key] = #{Native.try_convert(`value`)};
    }

    return result;
  }
end