Class: String

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
opal/opal/corelib/string.rb,
opal/opal/corelib/string/inheritance.rb

Defined Under Namespace

Classes: Wrapper

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?, normalize

Class Method Details

.inherited(klass) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
# File 'opal/opal/corelib/string/inheritance.rb', line 2

def self.inherited(klass)
  replace = Class.new(String::Wrapper)

  %x{
    klass.$$proto         = replace.$$proto;
    klass.$$proto.$$class = klass;
    klass.$$alloc         = replace.$$alloc;
    klass.$$parent        = #{String::Wrapper};

    klass.$allocate = replace.$allocate;
    klass.$new      = replace.$new;
  }
end

.new(str = '') ⇒ Object



14
15
16
# File 'opal/opal/corelib/string.rb', line 14

def self.new(str = '')
  `new String(str)`
end

.try_convert(what) ⇒ Object



8
9
10
11
12
# File 'opal/opal/corelib/string.rb', line 8

def self.try_convert(what)
  what.to_str
rescue
  nil
end

Instance Method Details

#%(data) ⇒ Object



18
19
20
21
22
23
24
# File 'opal/opal/corelib/string.rb', line 18

def %(data)
  if Array === data
    format(self, *data)
  else
    format(self, data)
  end
end

#*(count) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'opal/opal/corelib/string.rb', line 26

def *(count)
  %x{
    if (count < 1) {
      return '';
    }

    var result  = '',
        pattern = self;

    while (count > 0) {
      if (count & 1) {
        result += pattern;
      }

      count >>= 1;
      pattern += pattern;
    }

    return result;
  }
end

#+(other) ⇒ Object



48
49
50
51
52
# File 'opal/opal/corelib/string.rb', line 48

def +(other)
  other = Opal.coerce_to other, String, :to_str

  `self + #{other.to_s}`
end

#<<(other) ⇒ Object Also known as: capitalize!, chomp!, chop!, downcase!, gsub!, lstrip!, next!, reverse!, slice!, squeeze!, strip!, sub!, succ!, swapcase!, tr!, tr_s!, upcase!



73
74
75
# File 'opal/opal/corelib/string.rb', line 73

def <<(other)
  raise NotImplementedError, '#<< not supported. Mutable String methods are not supported in Opal.'
end

#<=>(other) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'opal/opal/corelib/string.rb', line 54

def <=>(other)
  if other.respond_to? :to_str
    other = other.to_str.to_s

    `self > other ? 1 : (self < other ? -1 : 0)`
  else
    %x{
      var cmp = #{other <=> self};

      if (cmp === nil) {
        return nil;
      }
      else {
        return cmp > 0 ? -1 : (cmp < 0 ? 1 : 0);
      }
    }
  end
end

#==(other) ⇒ Object Also known as: eql?, ===



77
78
79
80
81
# File 'opal/opal/corelib/string.rb', line 77

def ==(other)
  return false unless String === other

  `#{to_s} == #{other.to_s}`
end

#=~(other) ⇒ Object



86
87
88
89
90
91
92
93
94
# File 'opal/opal/corelib/string.rb', line 86

def =~(other)
  %x{
    if (other.$$is_string) {
      #{raise TypeError, 'type mismatch: String given'};
    }

    return #{other =~ self};
  }
end

#[](index, length = undefined) ⇒ Object Also known as: slice



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'opal/opal/corelib/string.rb', line 96

def [](index, length = undefined)
  %x{
    var size = self.length;

    if (index.$$is_range) {
      var exclude = index.exclude,
          length  = index.end,
          index   = index.begin;

      if (index < 0) {
        index += size;
      }

      if (length < 0) {
        length += size;
      }

      if (!exclude) {
        length += 1;
      }

      if (index > size) {
        return nil;
      }

      length = length - index;

      if (length < 0) {
        length = 0;
      }

      return self.substr(index, length);
    }

    if (index < 0) {
      index += self.length;
    }

    if (length == null) {
      if (index >= self.length || index < 0) {
        return nil;
      }

      return self.substr(index, 1);
    }

    if (index > self.length || index < 0) {
      return nil;
    }

    return self.substr(index, length);
  }
end

#capitalizeObject



150
151
152
# File 'opal/opal/corelib/string.rb', line 150

def capitalize
  `self.charAt(0).toUpperCase() + self.substr(1).toLowerCase()`
end

#casecmp(other) ⇒ Object



156
157
158
159
160
# File 'opal/opal/corelib/string.rb', line 156

def casecmp(other)
  other = Opal.coerce_to(other, String, :to_str).to_s

  `self.toLowerCase()` <=> `other.toLowerCase()`
end

#center(width, padstr = ' ') ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'opal/opal/corelib/string.rb', line 162

def center(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var ljustified = #{ljust ((width + @length) / 2).ceil, padstr},
        rjustified = #{rjust ((width + @length) / 2).floor, padstr};

    return rjustified + ljustified.slice(self.length);
  }
end

#chars(&block) ⇒ Object



180
181
182
183
184
# File 'opal/opal/corelib/string.rb', line 180

def chars(&block)
  return each_char.to_a unless block

  each_char(&block)
end

#chomp(separator = $/) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'opal/opal/corelib/string.rb', line 186

def chomp(separator = $/)
  return self if `separator === nil || self.length === 0`

  separator = Opal.coerce_to!(separator, String, :to_str).to_s

  %x{
    if (separator === "\n") {
      return self.replace(/\r?\n?$/, '');
    }
    else if (separator === "") {
      return self.replace(/(\r?\n)+$/, '');
    }
    else if (self.length > separator.length) {
      var tail = self.substr(self.length - separator.length, separator.length);

      if (tail === separator) {
        return self.substr(0, self.length - separator.length);
      }
    }
  }

  self
end

#chopObject



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'opal/opal/corelib/string.rb', line 212

def chop
  %x{
    var length = self.length;

    if (length <= 1) {
      return "";
    }

    if (self.charAt(length - 1) === "\n" && self.charAt(length - 2) === "\r") {
      return self.substr(0, length - 2);
    }
    else {
      return self.substr(0, length - 1);
    }
  }
end

#chrObject



231
232
233
# File 'opal/opal/corelib/string.rb', line 231

def chr
  `self.charAt(0)`
end

#cloneObject Also known as: dup



235
236
237
238
239
# File 'opal/opal/corelib/string.rb', line 235

def clone
  copy = `self.slice()`
  copy.initialize_clone(self)
  copy
end

#count(str) ⇒ Object



247
248
249
# File 'opal/opal/corelib/string.rb', line 247

def count(str)
  `(self.length - self.replace(new RegExp(str, 'g'), '').length) / str.length`
end

#downcaseObject



253
254
255
# File 'opal/opal/corelib/string.rb', line 253

def downcase
  `self.toLowerCase()`
end

#each_char(&block) ⇒ Object



259
260
261
262
263
264
265
266
267
268
269
# File 'opal/opal/corelib/string.rb', line 259

def each_char(&block)
  return enum_for :each_char unless block_given?

  %x{
    for (var i = 0, length = self.length; i < length; i++) {
      #{yield `self.charAt(i)`};
    }
  }

  self
end

#each_line(separator = $/) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'opal/opal/corelib/string.rb', line 271

def each_line(separator = $/)
  return split(separator) unless block_given?

  %x{
    var chomped  = #{chomp},
        trailing = self.length != chomped.length,
        splitted = chomped.split(separator);

    for (var i = 0, length = splitted.length; i < length; i++) {
      if (i < length - 1 || trailing) {
        #{yield `splitted[i] + separator`};
      }
      else {
        #{yield `splitted[i]`};
      }
    }
  }

  self
end

#empty?Boolean

Returns:



292
293
294
# File 'opal/opal/corelib/string.rb', line 292

def empty?
  `self.length === 0`
end

#end_with?(*suffixes) ⇒ Boolean

Returns:



296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'opal/opal/corelib/string.rb', line 296

def end_with?(*suffixes)
  %x{
    for (var i = 0, length = suffixes.length; i < length; i++) {
      var suffix = #{Opal.coerce_to(`suffixes[i]`, String, :to_str).to_s};

      if (self.length >= suffix.length &&
          self.substr(self.length - suffix.length, suffix.length) == suffix) {
        return true;
      }
    }
  }

  false
end

#freezeObject



1239
1240
1241
# File 'opal/opal/corelib/string.rb', line 1239

def freeze
  self
end

#frozen?Boolean

Returns:



1243
1244
1245
# File 'opal/opal/corelib/string.rb', line 1243

def frozen?
  true
end

#gsub(pattern, replace = undefined, &block) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'opal/opal/corelib/string.rb', line 314

def gsub(pattern, replace = undefined, &block)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = /#{Regexp.escape(pattern.to_str)}/
  end

  unless Regexp === pattern
    raise TypeError, "wrong argument type #{pattern.class} (expected Regexp)"
  end

  %x{
    var pattern = pattern.toString(),
        options = pattern.substr(pattern.lastIndexOf('/') + 1) + 'g',
        regexp  = pattern.substr(1, pattern.lastIndexOf('/') - 1);

    self.$sub.$$p = block;
    return self.$sub(new RegExp(regexp, options), replace);
  }
end

#hashObject



335
336
337
# File 'opal/opal/corelib/string.rb', line 335

def hash
  `self.toString()`
end

#hexObject



339
340
341
# File 'opal/opal/corelib/string.rb', line 339

def hex
  to_i 16
end

#include?(other) ⇒ Boolean

Returns:



343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'opal/opal/corelib/string.rb', line 343

def include?(other)
  %x{
    if (other.$$is_string) {
      return self.indexOf(other) !== -1;
    }
  }

  unless other.respond_to? :to_str
    raise TypeError, "no implicit conversion of #{other.class} into String"
  end

  `self.indexOf(#{other.to_str}) !== -1`
end

#index(what, offset = nil) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'opal/opal/corelib/string.rb', line 357

def index(what, offset = nil)
  if String === what
    what = what.to_s
  elsif what.respond_to? :to_str
    what = what.to_str.to_s
  elsif not Regexp === what
    raise TypeError, "type mismatch: #{what.class} given"
  end

  result = -1

  if offset
    offset = Opal.coerce_to offset, Integer, :to_int

    %x{
      var size = self.length;

      if (offset < 0) {
        offset = offset + size;
      }

      if (offset > size) {
        return nil;
      }
    }

    if Regexp === what
      result = (what =~ `self.substr(offset)`) || -1
    else
      result = `self.substr(offset).indexOf(what)`
    end

    %x{
      if (result !== -1) {
        result += offset;
      }
    }
  else
    if Regexp === what
      result = (what =~ self) || -1
    else
      result = `self.indexOf(what)`
    end
  end

  unless `result === -1`
    result
  end
end

#inspectObject



407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# File 'opal/opal/corelib/string.rb', line 407

def inspect
  %x{
    var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        meta      = {
          '\b': '\\b',
          '\t': '\\t',
          '\n': '\\n',
          '\f': '\\f',
          '\r': '\\r',
          '"' : '\\"',
          '\\': '\\\\'
        };

    escapable.lastIndex = 0;

    return escapable.test(self) ? '"' + self.replace(escapable, function(a) {
      var c = meta[a];

      return typeof c === 'string' ? c :
        '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
    }) + '"' : '"' + self + '"';
  }
end

#internObject Also known as: to_sym



431
432
433
# File 'opal/opal/corelib/string.rb', line 431

def intern
  self
end

#lengthObject Also known as: size



439
440
441
# File 'opal/opal/corelib/string.rb', line 439

def length
  `self.length`
end

#lines(separator = $/) ⇒ Object



435
436
437
# File 'opal/opal/corelib/string.rb', line 435

def lines(separator = $/)
  each_line(separator).to_a
end

#ljust(width, padstr = ' ') ⇒ Object



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'opal/opal/corelib/string.rb', line 443

def ljust(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var index  = -1,
        result = "";

    width -= self.length;

    while (++index < width) {
      result += padstr;
    }

    return self + result.slice(0, width);
  }
end

#lstripObject



467
468
469
# File 'opal/opal/corelib/string.rb', line 467

def lstrip
  `self.replace(/^\s*/, '')`
end

#match(pattern, pos = undefined, &block) ⇒ Object



473
474
475
476
477
478
479
480
481
482
483
# File 'opal/opal/corelib/string.rb', line 473

def match(pattern, pos = undefined, &block)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = /#{Regexp.escape(pattern.to_str)}/
  end

  unless Regexp === pattern
    raise TypeError, "wrong argument type #{pattern.class} (expected Regexp)"
  end

  pattern.match(self, pos, &block)
end

#nextObject Also known as: succ



485
486
487
488
489
490
491
492
493
494
495
496
# File 'opal/opal/corelib/string.rb', line 485

def next
  %x{
    if (self.length === 0) {
      return "";
    }

    var initial = self.substr(0, self.length - 1);
    var last    = String.fromCharCode(self.charCodeAt(self.length - 1) + 1);

    return initial + last;
  }
end

#ordObject



500
501
502
# File 'opal/opal/corelib/string.rb', line 500

def ord
  `self.charCodeAt(0)`
end

#partition(str) ⇒ Object



504
505
506
507
508
509
510
511
# File 'opal/opal/corelib/string.rb', line 504

def partition(str)
  %x{
    var result = self.split(str);
    var splitter = (result[0].length === self.length ? "" : str);

    return [result[0], splitter, result.slice(1).join(str.toString())];
  }
end

#reverseObject



513
514
515
# File 'opal/opal/corelib/string.rb', line 513

def reverse
  `self.split('').reverse().join('')`
end

#rindex(search, offset = undefined) ⇒ Object

TODO handle case where search is regexp



520
521
522
523
524
525
526
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
561
562
# File 'opal/opal/corelib/string.rb', line 520

def rindex(search, offset = undefined)
  %x{
    var search_type = (search == null ? Opal.NilClass : search.constructor);
    if (search_type != String && search_type != RegExp) {
      var msg = "type mismatch: " + search_type + " given";
      #{raise TypeError.new(`msg`)};
    }

    if (self.length == 0) {
      return search.length == 0 ? 0 : nil;
    }

    var result = -1;
    if (offset != null) {
      if (offset < 0) {
        offset = self.length + offset;
      }

      if (search_type == String) {
        result = self.lastIndexOf(search, offset);
      }
      else {
        result = self.substr(0, offset + 1).$reverse().search(search);
        if (result !== -1) {
          result = offset - result;
        }
      }
    }
    else {
      if (search_type == String) {
        result = self.lastIndexOf(search);
      }
      else {
        result = self.$reverse().search(search);
        if (result !== -1) {
          result = self.length - 1 - result;
        }
      }
    }

    return result === -1 ? nil : result;
  }
end

#rjust(width, padstr = ' ') ⇒ Object



564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'opal/opal/corelib/string.rb', line 564

def rjust(width, padstr = ' ')
  width  = Opal.coerce_to(width, Integer, :to_int)
  padstr = Opal.coerce_to(padstr, String, :to_str).to_s

  if padstr.empty?
    raise ArgumentError, 'zero width padding'
  end

  return self if `width <= self.length`

  %x{
    var chars     = Math.floor(width - self.length),
        patterns  = Math.floor(chars / padstr.length),
        result    = Array(patterns + 1).join(padstr),
        remaining = chars - result.length;

    return result + padstr.slice(0, remaining) + self;
  }
end

#rstripObject



584
585
586
# File 'opal/opal/corelib/string.rb', line 584

def rstrip
  `self.replace(/\s*$/, '')`
end

#scan(pattern, &block) ⇒ Object



588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'opal/opal/corelib/string.rb', line 588

def scan(pattern, &block)
  %x{
    if (pattern.global) {
      // should we clear it afterwards too?
      pattern.lastIndex = 0;
    }
    else {
      // rewrite regular expression to add the global flag to capture pre/post match
      pattern = new RegExp(pattern.source, 'g' + (pattern.multiline ? 'm' : '') + (pattern.ignoreCase ? 'i' : ''));
    }

    var result = [];
    var match;

    while ((match = pattern.exec(self)) != null) {
      var match_data = #{MatchData.new `pattern`, `match`};
      if (block === nil) {
        match.length == 1 ? result.push(match[0]) : result.push(match.slice(1));
      }
      else {
        match.length == 1 ? block(match[0]) : block.apply(self, match.slice(1));
      }
    }

    return (block !== nil ? self : result);
  }
end

#split(pattern = $; || ' ', limit = undefined) ⇒ Object



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# File 'opal/opal/corelib/string.rb', line 621

def split(pattern = $; || ' ', limit = undefined)
  %x{
    if (pattern === nil || pattern === undefined) {
      pattern = #{$;};
    }

    var result = [];
    if (limit !== undefined) {
      limit = #{Opal.coerce_to!(limit, Integer, :to_int)};
    }

    if (self.length === 0) {
      return [];
    }

    if (limit === 1) {
      return [self];
    }

    if (pattern && pattern.$$is_regexp) {
      var pattern_str = pattern.toString();

      /* Opal and JS's repr of an empty RE. */
      var blank_pattern = (pattern_str.substr(0, 3) == '/^/') ||
                (pattern_str.substr(0, 6) == '/(?:)/');

      /* This is our fast path */
      if (limit === undefined || limit === 0) {
        result = self.split(blank_pattern ? /(?:)/ : pattern);
      }
      else {
        /* RegExp.exec only has sane behavior with global flag */
        if (! pattern.global) {
          pattern = eval(pattern_str + 'g');
        }

        var match_data;
        var prev_index = 0;
        pattern.lastIndex = 0;

        while ((match_data = pattern.exec(self)) !== null) {
          var segment = self.slice(prev_index, match_data.index);
          result.push(segment);

          prev_index = pattern.lastIndex;

          if (match_data[0].length === 0) {
            if (blank_pattern) {
              /* explicitly split on JS's empty RE form.*/
              pattern = /(?:)/;
            }

            result = self.split(pattern);
            /* with "unlimited", ruby leaves a trail on blanks. */
            if (limit !== undefined && limit < 0 && blank_pattern) {
              result.push('');
            }

            prev_index = undefined;
            break;
          }

          if (limit !== undefined && limit > 1 && result.length + 1 == limit) {
            break;
          }
        }

        if (prev_index !== undefined) {
          result.push(self.slice(prev_index, self.length));
        }
      }
    }
    else {
      var splitted = 0, start = 0, lim = 0;

      if (pattern === nil || pattern === undefined) {
        pattern = ' '
      } else {
        pattern = #{Opal.try_convert(pattern, String, :to_str).to_s};
      }

      var string = (pattern == ' ') ? self.replace(/[\r\n\t\v]\s+/g, ' ')
                                    : self;
      var cursor = -1;
      while ((cursor = string.indexOf(pattern, start)) > -1 && cursor < string.length) {
        if (splitted + 1 === limit) {
          break;
        }

        if (pattern == ' ' && cursor == start) {
          start = cursor + 1;
          continue;
        }

        result.push(string.substr(start, pattern.length ? cursor - start : 1));
        splitted++;

        start = cursor + (pattern.length ? pattern.length : 1);
      }

      if (string.length > 0 && (limit < 0 || string.length > start)) {
        if (string.length == start) {
          result.push('');
        }
        else {
          result.push(string.substr(start, string.length));
        }
      }
    }

    if (limit === undefined || limit === 0) {
      while (result[result.length-1] === '') {
        result.length = result.length - 1;
      }
    }

    if (limit > 0) {
      var tail = result.slice(limit - 1).join('');
      result.splice(limit - 1, result.length - 1, tail);
    }

    return result;
  }
end

#squeeze(*sets) ⇒ Object



746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
# File 'opal/opal/corelib/string.rb', line 746

def squeeze(*sets)
  %x{
    if (sets.length === 0) {
      return self.replace(/(.)\1+/g, '$1');
    }
  }

  %x{
    var set = #{Opal.coerce_to(`sets[0]`, String, :to_str).chars};

    for (var i = 1, length = sets.length; i < length; i++) {
      set = #{`set` & Opal.coerce_to(`sets[i]`, String, :to_str).chars};
    }

    if (set.length === 0) {
      return self;
    }

    return self.replace(new RegExp("([" + #{Regexp.escape(`set`.join)} + "])\\1+", "g"), "$1");
  }
end

#start_with?(*prefixes) ⇒ Boolean

Returns:



770
771
772
773
774
775
776
777
778
779
780
781
782
# File 'opal/opal/corelib/string.rb', line 770

def start_with?(*prefixes)
  %x{
    for (var i = 0, length = prefixes.length; i < length; i++) {
      var prefix = #{Opal.coerce_to(`prefixes[i]`, String, :to_str).to_s};

      if (self.indexOf(prefix) === 0) {
        return true;
      }
    }

    return false;
  }
end

#stripObject



784
785
786
# File 'opal/opal/corelib/string.rb', line 784

def strip
  `self.replace(/^\s*/, '').replace(/\s*$/, '')`
end

#sub(pattern, replace = undefined, &block) ⇒ Object



803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'opal/opal/corelib/string.rb', line 803

def sub(pattern, replace = undefined, &block)
  %x{
    if (typeof(pattern) !== 'string' && !pattern.$$is_regexp) {
      pattern = #{Opal.coerce_to! pattern, String, :to_str};
    }

    if (replace !== undefined) {
      if (#{replace.is_a?(Hash)}) {
        return self.replace(pattern, function(str) {
          var value = #{replace[str]};

          return (value == null) ? nil : #{value.to_s};
        });
      }
      else {
        if (typeof(replace) !== 'string') {
          replace = #{Opal.coerce_to! replace, String, :to_str};
        }

        replace = convertReplace(replace);
        return self.replace(pattern, replace);
      }

    }
    else if (block != null && block !== nil) {
      return self.replace(pattern, function() {
        // FIXME: this should be a formal MatchData object with all the goodies
        var match_data = []
        for (var i = 0, len = arguments.length; i < len; i++) {
          var arg = arguments[i];
          if (arg == undefined) {
            match_data.push(nil);
          }
          else {
            match_data.push(arg);
          }
        }

        var str = match_data.pop();
        var offset = match_data.pop();
        var match_len = match_data.length;

        // $1, $2, $3 not being parsed correctly in Ruby code
        for (var i = 1; i < match_len; i++) {
          Opal.gvars[String(i)] = match_data[i];
        }
        #{$& = `match_data[0]`};
        #{$~ = `match_data`};
        return block(match_data[0]);
      });
    }
    else {
      #{raise ArgumentError, 'wrong number of arguments (1 for 2)'}
    }
  }
end

#sum(n = 16) ⇒ Object



865
866
867
868
869
870
871
872
873
874
875
# File 'opal/opal/corelib/string.rb', line 865

def sum(n = 16)
  %x{
    var result = 0;

    for (var i = 0, length = self.length; i < length; i++) {
      result += (self.charCodeAt(i) % ((1 << n) - 1));
    }

    return result;
  }
end

#swapcaseObject



877
878
879
880
881
882
883
884
885
886
887
888
889
# File 'opal/opal/corelib/string.rb', line 877

def swapcase
  %x{
    var str = self.replace(/([a-z]+)|([A-Z]+)/g, function($0,$1,$2) {
      return $1 ? $0.toUpperCase() : $0.toLowerCase();
    });

    if (self.constructor === String) {
      return str;
    }

    return #{self.class.new `str`};
  }
end

#to_fObject



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
# File 'opal/opal/corelib/string.rb', line 893

def to_f
  %x{
    if (self.charAt(0) === '_') {
      return 0;
    }

    var result = parseFloat(self.replace(/_/g, ''));

    if (isNaN(result) || result == Infinity || result == -Infinity) {
      return 0;
    }
    else {
      return result;
    }
  }
end

#to_i(base = 10) ⇒ Object



910
911
912
913
914
915
916
917
918
919
920
# File 'opal/opal/corelib/string.rb', line 910

def to_i(base = 10)
  %x{
    var result = parseInt(self, base);

    if (isNaN(result)) {
      return 0;
    }

    return result;
  }
end

#to_procObject



922
923
924
925
926
927
928
929
930
931
# File 'opal/opal/corelib/string.rb', line 922

def to_proc
  # Give name to self in case this proc is passed to instance_eval
  sym = self

  proc do |*args, &block|
    raise ArgumentError, "no receiver given" if args.empty?
    obj = args.shift
    obj.__send__(sym, *args, &block)
  end
end

#to_sObject Also known as: to_str



933
934
935
# File 'opal/opal/corelib/string.rb', line 933

def to_s
  `self.toString()`
end

#tr(from, to) ⇒ Object



941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'opal/opal/corelib/string.rb', line 941

def tr(from, to)
  %x{
    if (from.length == 0 || from === to) {
      return self;
    }

    var subs = {};
    var from_chars = from.split('');
    var from_length = from_chars.length;
    var to_chars = to.split('');
    var to_length = to_chars.length;

    var inverse = false;
    var global_sub = null;
    if (from_chars[0] === '^') {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    var in_range = false;
    for (var i = 0; i < from_length; i++) {
      var ch = from_chars[i];
      if (last_from == null) {
        last_from = ch;
        from_chars_expanded.push(ch);
      }
      else if (ch === '-') {
        if (last_from === '-') {
          from_chars_expanded.push('-');
          from_chars_expanded.push('-');
        }
        else if (i == from_length - 1) {
          from_chars_expanded.push('-');
        }
        else {
          in_range = true;
        }
      }
      else if (in_range) {
        var start = last_from.charCodeAt(0) + 1;
        var end = ch.charCodeAt(0);
        for (var c = start; c < end; c++) {
          from_chars_expanded.push(String.fromCharCode(c));
        }
        from_chars_expanded.push(ch);
        in_range = null;
        last_from = null;
      }
      else {
        from_chars_expanded.push(ch);
      }
    }

    from_chars = from_chars_expanded;
    from_length = from_chars.length;

    if (inverse) {
      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        var in_range = false;
        for (var i = 0; i < to_length; i++) {
          var ch = to_chars[i];
          if (last_from == null) {
            last_from = ch;
            to_chars_expanded.push(ch);
          }
          else if (ch === '-') {
            if (last_to === '-') {
              to_chars_expanded.push('-');
              to_chars_expanded.push('-');
            }
            else if (i == to_length - 1) {
              to_chars_expanded.push('-');
            }
            else {
              in_range = true;
            }
          }
          else if (in_range) {
            var start = last_from.charCodeAt(0) + 1;
            var end = ch.charCodeAt(0);
            for (var c = start; c < end; c++) {
              to_chars_expanded.push(String.fromCharCode(c));
            }
            to_chars_expanded.push(ch);
            in_range = null;
            last_from = null;
          }
          else {
            to_chars_expanded.push(ch);
          }
        }

        to_chars = to_chars_expanded;
        to_length = to_chars.length;
      }

      var length_diff = from_length - to_length;
      if (length_diff > 0) {
        var pad_char = (to_length > 0 ? to_chars[to_length - 1] : '');
        for (var i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = to_chars[i];
      }
    }

    var new_str = ''
    for (var i = 0, length = self.length; i < length; i++) {
      var ch = self.charAt(i);
      var sub = subs[ch];
      if (inverse) {
        new_str += (sub == null ? global_sub : ch);
      }
      else {
        new_str += (sub != null ? sub : ch);
      }
    }
    return new_str;
  }
end

#tr_s(from, to) ⇒ Object



1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
# File 'opal/opal/corelib/string.rb', line 1078

def tr_s(from, to)
  %x{
    if (from.length == 0) {
      return self;
    }

    var subs = {};
    var from_chars = from.split('');
    var from_length = from_chars.length;
    var to_chars = to.split('');
    var to_length = to_chars.length;

    var inverse = false;
    var global_sub = null;
    if (from_chars[0] === '^') {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    var in_range = false;
    for (var i = 0; i < from_length; i++) {
      var ch = from_chars[i];
      if (last_from == null) {
        last_from = ch;
        from_chars_expanded.push(ch);
      }
      else if (ch === '-') {
        if (last_from === '-') {
          from_chars_expanded.push('-');
          from_chars_expanded.push('-');
        }
        else if (i == from_length - 1) {
          from_chars_expanded.push('-');
        }
        else {
          in_range = true;
        }
      }
      else if (in_range) {
        var start = last_from.charCodeAt(0) + 1;
        var end = ch.charCodeAt(0);
        for (var c = start; c < end; c++) {
          from_chars_expanded.push(String.fromCharCode(c));
        }
        from_chars_expanded.push(ch);
        in_range = null;
        last_from = null;
      }
      else {
        from_chars_expanded.push(ch);
      }
    }

    from_chars = from_chars_expanded;
    from_length = from_chars.length;

    if (inverse) {
      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        var in_range = false;
        for (var i = 0; i < to_length; i++) {
          var ch = to_chars[i];
          if (last_from == null) {
            last_from = ch;
            to_chars_expanded.push(ch);
          }
          else if (ch === '-') {
            if (last_to === '-') {
              to_chars_expanded.push('-');
              to_chars_expanded.push('-');
            }
            else if (i == to_length - 1) {
              to_chars_expanded.push('-');
            }
            else {
              in_range = true;
            }
          }
          else if (in_range) {
            var start = last_from.charCodeAt(0) + 1;
            var end = ch.charCodeAt(0);
            for (var c = start; c < end; c++) {
              to_chars_expanded.push(String.fromCharCode(c));
            }
            to_chars_expanded.push(ch);
            in_range = null;
            last_from = null;
          }
          else {
            to_chars_expanded.push(ch);
          }
        }

        to_chars = to_chars_expanded;
        to_length = to_chars.length;
      }

      var length_diff = from_length - to_length;
      if (length_diff > 0) {
        var pad_char = (to_length > 0 ? to_chars[to_length - 1] : '');
        for (var i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

      for (var i = 0; i < from_length; i++) {
        subs[from_chars[i]] = to_chars[i];
      }
    }
    var new_str = ''
    var last_substitute = null
    for (var i = 0, length = self.length; i < length; i++) {
      var ch = self.charAt(i);
      var sub = subs[ch]
      if (inverse) {
        if (sub == null) {
          if (last_substitute == null) {
            new_str += global_sub;
            last_substitute = true;
          }
        }
        else {
          new_str += ch;
          last_substitute = null;
        }
      }
      else {
        if (sub != null) {
          if (last_substitute == null || last_substitute !== sub) {
            new_str += sub;
            last_substitute = sub;
          }
        }
        else {
          new_str += ch;
          last_substitute = null;
        }
      }
    }
    return new_str;
  }
end

#upcaseObject



1233
1234
1235
# File 'opal/opal/corelib/string.rb', line 1233

def upcase
  `self.toUpperCase()`
end