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.



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
566
567
568
569
570
571
572
573
574
# File 'opal/stdlib/native.rb', line 535

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

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

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

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

        keys.push(key);
      }

      return self;
    }

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

Instance Method Details

#_initializeObject



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

alias _initialize initialize

#to_jsonObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'opal/stdlib/json.rb', line 154

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

all values.

Returns:

  • a JavaScript object with the same keys but calling #to_n on



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
# File 'opal/stdlib/native.rb', line 578

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`, `value`)};
    }

    return result;
  }
end