Class: Hash

Inherits:
Object show all
Defined in:
/Users/elia/Code/opal-docs/opal/stdlib/json.rb,
/Users/elia/Code/opal-docs/opal/stdlib/native.rb

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Hash


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
561
562
563
564
565
# File '/Users/elia/Code/opal-docs/opal/stdlib/native.rb', line 532

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


530
# File '/Users/elia/Code/opal-docs/opal/stdlib/native.rb', line 530

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 '/Users/elia/Code/opal-docs/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.


569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File '/Users/elia/Code/opal-docs/opal/stdlib/native.rb', line 569

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;
      }

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

    return result;
  }
end