Class: String

Inherits:
Object show all
Includes:
Comparable
Defined in:
opal/opal/corelib/string.rb,
opal/opal/corelib/complex.rb,
opal/opal/corelib/rational.rb,
opal/opal/corelib/unsupported.rb,
opal/opal/corelib/string/unpack.rb,
opal/opal/corelib/string/encoding.rb,
opal/opal/corelib/marshal/write_buffer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?, #clamp

Constructor Details

#initialize(str = undefined, encoding: nil, capacity: nil) ⇒ String

Our initialize method does nothing, the string value setup is being done by String.new. Therefore not all kinds of subclassing will work. As a rule of thumb, when subclassing String, either make sure to override .new or make sure that the first argument given to a constructor is a string we want our subclass-string to hold.



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

def initialize(str = undefined, encoding: nil, capacity: nil)
end

Instance Attribute Details

#encodingObject (readonly)

Returns the value of attribute encoding.



305
306
307
# File 'opal/opal/corelib/string/encoding.rb', line 305

def encoding
  @encoding
end

#internal_encodingObject (readonly)

Returns the value of attribute internal_encoding.



306
307
308
# File 'opal/opal/corelib/string/encoding.rb', line 306

def internal_encoding
  @internal_encoding
end

Class Method Details

._load(*args) ⇒ Object



1833
1834
1835
# File 'opal/opal/corelib/string.rb', line 1833

def self._load(*args)
  new(*args)
end

.new(*args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'opal/opal/corelib/string.rb', line 32

def self.new(*args)
  %x{
    var str = args[0] || "";
    var opts = args[args.length-1];
    str = $coerce_to(str, #{String}, 'to_str');
    if (opts && opts.$$is_hash) {
      if (opts.$$smap.encoding) str = str.$force_encoding(opts.$$smap.encoding);
    }
    str = new self.$$constructor(str);
    if (!str.$initialize.$$pristine) #{`str`.initialize(*args)};
    return str;
  }
end

.try_convert(what) ⇒ Object



28
29
30
# File 'opal/opal/corelib/string.rb', line 28

def self.try_convert(what)
  Opal.coerce_to?(what, String, :to_str)
end

Instance Method Details

#%(data) ⇒ Object



54
55
56
57
58
59
60
# File 'opal/opal/corelib/string.rb', line 54

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

#*(count) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'opal/opal/corelib/string.rb', line 62

def *(count)
  %x{
    count = $coerce_to(count, #{Integer}, 'to_int');

    if (count < 0) {
      #{raise ArgumentError, 'negative argument'}
    }

    if (count === 0) {
      return self.$$cast('');
    }

    var result = '',
        string = self.toString();

    // All credit for the bit-twiddling magic code below goes to Mozilla
    // polyfill implementation of String.prototype.repeat() posted here:
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat

    if (string.length * count >= 1 << 28) {
      #{raise RangeError, 'multiply count must not overflow maximum string size'}
    }

    for (;;) {
      if ((count & 1) === 1) {
        result += string;
      }
      count >>>= 1;
      if (count === 0) {
        break;
      }
      string += string;
    }

    return self.$$cast(result);
  }
end

#+(other) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
# File 'opal/opal/corelib/string.rb', line 100

def +(other)
  other = `$coerce_to(#{other}, #{String}, 'to_str')`

  %x{
    if (other == "" && self.$$class === Opal.String) return #{self};
    if (self == "" && other.$$class === Opal.String) return #{other};
    var out = self + other;
    if (self.encoding === out.encoding && other.encoding === out.encoding) return out;
    if (self.encoding.name === "UTF-8" || other.encoding.name === "UTF-8") return out;
    return Opal.enc(out, self.encoding);
  }
end

#-@Object



1864
1865
1866
1867
1868
1869
1870
1871
# File 'opal/opal/corelib/string.rb', line 1864

def -@
  %x{
    if (typeof self === 'string') return self;
    if (self.$$frozen === true) return self;
    if (self.encoding.name == 'UTF-8' && self.internal_encoding.name == 'UTF-8') return self.toString();
    return self.$dup().$freeze();
  }
end

#<<Object



30
31
32
# File 'opal/opal/corelib/unsupported.rb', line 30

def <<(*)
  raise NotImplementedError, `ERROR` % '<<'
end

#<=>(other) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'opal/opal/corelib/string.rb', line 113

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?, ===



132
133
134
135
136
137
138
139
140
141
142
# File 'opal/opal/corelib/string.rb', line 132

def ==(other)
  %x{
    if (other.$$is_string) {
      return self.toString() === other.toString();
    }
    if ($respond_to(other, '$to_str')) {
      return #{other == self};
    }
    return false;
  }
end

#=~(other) ⇒ Object



147
148
149
150
151
152
153
154
155
# File 'opal/opal/corelib/string.rb', line 147

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

    return #{other =~ self};
  }
end

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



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'opal/opal/corelib/string.rb', line 157

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

    if (index.$$is_range) {
      exclude = index.excl;
      length  = $coerce_to(index.end, #{Integer}, 'to_int');
      index   = $coerce_to(index.begin, #{Integer}, 'to_int');

      if (Math.abs(index) > size) {
        return nil;
      }

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

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

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

      length = length - index;

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

      return self.$$cast(self.substr(index, length));
    }


    if (index.$$is_string) {
      if (length != null) {
        #{raise TypeError}
      }
      return self.indexOf(index) !== -1 ? self.$$cast(index) : nil;
    }


    if (index.$$is_regexp) {
      var match = self.match(index);

      if (match === null) {
        #{$~ = nil}
        return nil;
      }

      #{$~ = MatchData.new(`index`, `match`)}

      if (length == null) {
        return self.$$cast(match[0]);
      }

      length = $coerce_to(length, #{Integer}, 'to_int');

      if (length < 0 && -length < match.length) {
        return self.$$cast(match[length += match.length]);
      }

      if (length >= 0 && length < match.length) {
        return self.$$cast(match[length]);
      }

      return nil;
    }


    index = $coerce_to(index, #{Integer}, 'to_int');

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

    if (length == null) {
      if (index >= size || index < 0) {
        return nil;
      }
      return self.$$cast(self.substr(index, 1));
    }

    length = $coerce_to(length, #{Integer}, 'to_int');

    if (length < 0) {
      return nil;
    }

    if (index > size || index < 0) {
      return nil;
    }

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

#[]=Object



106
107
108
# File 'opal/opal/corelib/unsupported.rb', line 106

def []=(*)
  raise NotImplementedError, `ERROR` % '[]='
end

#__id__Object Also known as: object_id



22
23
24
# File 'opal/opal/corelib/string.rb', line 22

def __id__
  `self.toString()`
end

#__marshal__(buffer) ⇒ Object



38
39
40
41
42
43
44
45
# File 'opal/opal/corelib/marshal/write_buffer.rb', line 38

def __marshal__(buffer)
  buffer.save_link(self)
  buffer.write_ivars_prefix(self)
  buffer.write_extends(self)
  buffer.write_user_class(String, self)
  buffer.append('"')
  buffer.write_string(self)
end

#ascii_only?Boolean

Returns:



694
695
696
697
698
699
700
# File 'opal/opal/corelib/string.rb', line 694

def ascii_only?
  # non-ASCII-compatible encoding must return false
  %x{
    if (!self.encoding.ascii) return false;
    return /^[\x00-\x7F]*$/.test(self);
  }
end

#bObject



257
258
259
# File 'opal/opal/corelib/string.rb', line 257

def b
  `new String(#{self})`.force_encoding('binary')
end

#bytesObject



327
328
329
330
331
332
333
334
335
336
337
338
# File 'opal/opal/corelib/string/encoding.rb', line 327

def bytes
  # REMIND: required when running in strict mode, otherwise the following error will be thrown:
  # Cannot create property 'bytes' on string 'abc'
  %x{
    if (typeof self === 'string') {
      return #{`new String(self)`.each_byte.to_a};
    }
  }

  @bytes ||= each_byte.to_a
  @bytes.dup
end

#bytesizeObject



315
316
317
# File 'opal/opal/corelib/string/encoding.rb', line 315

def bytesize
  @internal_encoding.bytesize(self)
end

#capitalizeObject



261
262
263
# File 'opal/opal/corelib/string.rb', line 261

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

#capitalize!Object



34
35
36
# File 'opal/opal/corelib/unsupported.rb', line 34

def capitalize!(*)
  raise NotImplementedError, `ERROR` % 'capitalize!'
end

#casecmp(other) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
276
# File 'opal/opal/corelib/string.rb', line 265

def casecmp(other)
  return nil unless other.respond_to?(:to_str)
  other = `$coerce_to(other, #{String}, 'to_str')`.to_s
  %x{
    var ascii_only = /^[\x00-\x7F]*$/;
    if (ascii_only.test(self) && ascii_only.test(other)) {
      self = self.toLowerCase();
      other = other.toLowerCase();
    }
  }
  self <=> other
end

#casecmp?(other) ⇒ Boolean

Returns:



278
279
280
281
282
283
284
285
286
287
# File 'opal/opal/corelib/string.rb', line 278

def casecmp?(other)
  %x{
    var cmp = #{casecmp(other)};
    if (cmp === nil) {
      return nil;
    } else {
      return cmp === 0;
    }
  }
end

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



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'opal/opal/corelib/string.rb', line 289

def center(width, padstr = ' ')
  width  = `$coerce_to(#{width}, #{Integer}, 'to_int')`
  padstr = `$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 + `self.length`) / 2).ceil, padstr},
        rjustified = #{rjust ((width + `self.length`) / 2).floor, padstr};

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

#chars(&block) ⇒ Object



348
349
350
351
352
# File 'opal/opal/corelib/string/encoding.rb', line 348

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

  each_char(&block)
end

#chomp(separator = $/) ⇒ Object



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'opal/opal/corelib/string.rb', line 307

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

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

  %x{
    var result;

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

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

    if (result != null) {
      return self.$$cast(result);
    }
  }

  self
end

#chomp!Object



38
39
40
# File 'opal/opal/corelib/unsupported.rb', line 38

def chomp!(*)
  raise NotImplementedError, `ERROR` % 'chomp!'
end

#chopObject



337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'opal/opal/corelib/string.rb', line 337

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

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

    return self.$$cast(result);
  }
end

#chop!Object



42
43
44
# File 'opal/opal/corelib/unsupported.rb', line 42

def chop!(*)
  raise NotImplementedError, `ERROR` % 'chop!'
end

#chrObject



353
354
355
# File 'opal/opal/corelib/string.rb', line 353

def chr
  `self.charAt(0)`
end

#clearObject



110
111
112
# File 'opal/opal/corelib/unsupported.rb', line 110

def clear(*)
  raise NotImplementedError, `ERROR` % 'clear'
end

#cloneObject



357
358
359
360
361
362
# File 'opal/opal/corelib/string.rb', line 357

def clone
  copy = `new String(self)`
  copy.copy_singleton_methods(self)
  copy.initialize_clone(self)
  copy
end

#codepoints(&block) ⇒ Object



364
365
366
367
368
# File 'opal/opal/corelib/string/encoding.rb', line 364

def codepoints(&block)
  # If a block is given, which is a deprecated form, works the same as each_codepoint.
  return each_codepoint(&block) if block_given?
  each_codepoint.to_a
end

#count(*sets) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
# File 'opal/opal/corelib/string.rb', line 370

def count(*sets)
  %x{
    if (sets.length === 0) {
      #{raise ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'}
    }
    var char_class = char_class_from_char_sets(sets);
    if (char_class === null) {
      return 0;
    }
    return self.length - self.replace(new RegExp(char_class, 'g'), '').length;
  }
end

#delete(*sets) ⇒ Object



383
384
385
386
387
388
389
390
391
392
393
394
# File 'opal/opal/corelib/string.rb', line 383

def delete(*sets)
  %x{
    if (sets.length === 0) {
      #{raise ArgumentError, 'ArgumentError: wrong number of arguments (0 for 1+)'}
    }
    var char_class = char_class_from_char_sets(sets);
    if (char_class === null) {
      return self;
    }
    return self.$$cast(self.replace(new RegExp(char_class, 'g'), ''));
  }
end

#delete_prefix(prefix) ⇒ Object



396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'opal/opal/corelib/string.rb', line 396

def delete_prefix(prefix)
  %x{
    if (!prefix.$$is_string) {
      prefix = $coerce_to(prefix, #{String}, 'to_str');
    }

    if (self.slice(0, prefix.length) === prefix) {
      return self.$$cast(self.slice(prefix.length));
    } else {
      return self;
    }
  }
end

#delete_suffix(suffix) ⇒ Object



410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'opal/opal/corelib/string.rb', line 410

def delete_suffix(suffix)
  %x{
    if (!suffix.$$is_string) {
      suffix = $coerce_to(suffix, #{String}, 'to_str');
    }

    if (self.slice(self.length - suffix.length) === suffix) {
      return self.$$cast(self.slice(0, self.length - suffix.length));
    } else {
      return self;
    }
  }
end

#downcaseObject



424
425
426
# File 'opal/opal/corelib/string.rb', line 424

def downcase
  `self.$$cast(self.toLowerCase())`
end

#downcase!Object



46
47
48
# File 'opal/opal/corelib/unsupported.rb', line 46

def downcase!(*)
  raise NotImplementedError, `ERROR` % 'downcase!'
end

#dupObject Also known as: +@



364
365
366
367
368
# File 'opal/opal/corelib/string.rb', line 364

def dup
  copy = `new String(self)`
  copy.initialize_dup(self)
  copy
end

#each_byte(&block) ⇒ Object



319
320
321
322
323
324
325
# File 'opal/opal/corelib/string/encoding.rb', line 319

def each_byte(&block)
  return enum_for(:each_byte) { bytesize } unless block_given?

  @internal_encoding.each_byte(self, &block)

  self
end

#each_char(&block) ⇒ Object



340
341
342
343
344
345
346
# File 'opal/opal/corelib/string/encoding.rb', line 340

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

  @encoding.each_char(self, &block)

  self
end

#each_codepoint(&block) ⇒ Object



354
355
356
357
358
359
360
361
362
# File 'opal/opal/corelib/string/encoding.rb', line 354

def each_codepoint(&block)
  return enum_for :each_codepoint unless block_given?
  %x{
    for (var i = 0, length = self.length; i < length; i++) {
      #{yield `self.codePointAt(i)`};
    }
  }
  self
end

#each_line(separator = $/, &block) ⇒ Object



428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'opal/opal/corelib/string.rb', line 428

def each_line(separator = $/, &block)
  return enum_for :each_line, separator unless block_given?

  %x{
    if (separator === nil) {
      Opal.yield1(block, self);

      return self;
    }

    separator = $coerce_to(separator, #{String}, 'to_str')

    var a, i, n, length, chomped, trailing, splitted;

    if (separator.length === 0) {
      for (a = self.split(/(\n{2,})/), i = 0, n = a.length; i < n; i += 2) {
        if (a[i] || a[i + 1]) {
          var value = (a[i] || "") + (a[i + 1] || "");
          Opal.yield1(block, self.$$cast(value));
        }
      }

      return self;
    }

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

    for (i = 0, length = splitted.length; i < length; i++) {
      if (i < length - 1 || trailing) {
        Opal.yield1(block, self.$$cast(splitted[i] + separator));
      }
      else {
        Opal.yield1(block, self.$$cast(splitted[i]));
      }
    }
  }

  self
end

#empty?Boolean

Returns:



470
471
472
# File 'opal/opal/corelib/string.rb', line 470

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

#encode(encoding) ⇒ Object



370
371
372
# File 'opal/opal/corelib/string/encoding.rb', line 370

def encode(encoding)
  `Opal.enc(self, encoding)`
end

#encode!Object



114
115
116
# File 'opal/opal/corelib/unsupported.rb', line 114

def encode!(*)
  raise NotImplementedError, `ERROR` % 'encode!'
end

#end_with?(*suffixes) ⇒ Boolean

Returns:



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

def end_with?(*suffixes)
  %x{
    for (var i = 0, length = suffixes.length; i < length; i++) {
      var suffix = $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

#force_encoding(encoding) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'opal/opal/corelib/string/encoding.rb', line 374

def force_encoding(encoding)
  %x{
    var str = self;

    if (encoding === str.encoding) { return str; }

    encoding = #{Opal.coerce_to!(encoding, String, :to_s)};
    encoding = #{Encoding.find(encoding)};

    if (encoding === str.encoding) { return str; }

    str = Opal.set_encoding(str, encoding);

    return str;
  }
end

#freezeObject



1854
1855
1856
1857
1858
1859
1860
# File 'opal/opal/corelib/string.rb', line 1854

def freeze
  %x{
    if (typeof self === 'string') return self;
    self.$$frozen = true;
    return self;
  }
end

#frozen?Boolean

Returns:



1873
1874
1875
# File 'opal/opal/corelib/string.rb', line 1873

def frozen?
  `typeof self === 'string' || self.$$frozen === true`
end

#getbyte(idx) ⇒ Object



391
392
393
394
395
396
397
# File 'opal/opal/corelib/string/encoding.rb', line 391

def getbyte(idx)
  string_bytes = bytes
  idx = Opal.coerce_to!(idx, Integer, :to_int)
  return if string_bytes.length < idx

  string_bytes[idx]
end

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



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
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
563
# File 'opal/opal/corelib/string.rb', line 491

def gsub(pattern, replacement = undefined, &block)
  %x{
    if (replacement === undefined && block === nil) {
      return #{enum_for :gsub, pattern};
    }

    var result = '', match_data = nil, index = 0, match, _replacement;

    if (pattern.$$is_regexp) {
      pattern = Opal.global_multiline_regexp(pattern);
    } else {
      pattern = $coerce_to(pattern, #{String}, 'to_str');
      pattern = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gm');
    }

    var lastIndex;
    while (true) {
      match = pattern.exec(self);

      if (match === null) {
        #{$~ = nil}
        result += self.slice(index);
        break;
      }

      match_data = #{MatchData.new `pattern`, `match`};

      if (replacement === undefined) {
        lastIndex = pattern.lastIndex;
        _replacement = block(match[0]);
        pattern.lastIndex = lastIndex; // save and restore lastIndex
      }
      else if (replacement.$$is_hash) {
        _replacement = #{`replacement`[`match[0]`].to_s};
      }
      else {
        if (!replacement.$$is_string) {
          replacement = $coerce_to(replacement, #{String}, 'to_str');
        }
        _replacement = replacement.replace(/([\\]+)([0-9+&`'])/g, function (original, slashes, command) {
          if (slashes.length % 2 === 0) {
            return original;
          }
          switch (command) {
          case "+":
            for (var i = match.length - 1; i > 0; i--) {
              if (match[i] !== undefined) {
                return slashes.slice(1) + match[i];
              }
            }
            return '';
          case "&": return slashes.slice(1) + match[0];
          case "`": return slashes.slice(1) + self.slice(0, match.index);
          case "'": return slashes.slice(1) + self.slice(match.index + match[0].length);
          default:  return slashes.slice(1) + (match[command] || '');
          }
        }).replace(/\\\\/g, '\\');
      }

      if (pattern.lastIndex === match.index) {
        result += (self.slice(index, match.index) + _replacement + (self[match.index] || ""));
        pattern.lastIndex += 1;
      }
      else {
        result += (self.slice(index, match.index) + _replacement)
      }
      index = pattern.lastIndex;
    }

    #{$~ = `match_data`}
    return self.$$cast(result);
  }
end

#gsub!Object



50
51
52
# File 'opal/opal/corelib/unsupported.rb', line 50

def gsub!(*)
  raise NotImplementedError, `ERROR` % 'gsub!'
end

#hashObject



565
566
567
# File 'opal/opal/corelib/string.rb', line 565

def hash
  `self.toString()`
end

#hexObject



569
570
571
# File 'opal/opal/corelib/string.rb', line 569

def hex
  to_i 16
end

#include?(other) ⇒ Boolean

Returns:



573
574
575
576
577
578
579
580
# File 'opal/opal/corelib/string.rb', line 573

def include?(other)
  %x{
    if (!other.$$is_string) {
      other = $coerce_to(other, #{String}, 'to_str');
    }
    return self.indexOf(other) !== -1;
  }
end

#index(search, offset = undefined) ⇒ Object



582
583
584
585
586
587
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
615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'opal/opal/corelib/string.rb', line 582

def index(search, offset = undefined)
  %x{
    var index,
        match,
        regex;

    if (offset === undefined) {
      offset = 0;
    } else {
      offset = $coerce_to(offset, #{Integer}, 'to_int');
      if (offset < 0) {
        offset += self.length;
        if (offset < 0) {
          return nil;
        }
      }
    }

    if (search.$$is_regexp) {
      regex = Opal.global_multiline_regexp(search);
      while (true) {
        match = regex.exec(self);
        if (match === null) {
          #{$~ = nil};
          index = -1;
          break;
        }
        if (match.index >= offset) {
          #{$~ = MatchData.new(`regex`, `match`)}
          index = match.index;
          break;
        }
        regex.lastIndex = match.index + 1;
      }
    } else {
      search = $coerce_to(search, #{String}, 'to_str');
      if (search.length === 0 && offset > self.length) {
        index = -1;
      } else {
        index = self.indexOf(search, offset);
      }
    }

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

#initialize_copy(other) ⇒ Object



399
400
401
402
403
404
# File 'opal/opal/corelib/string/encoding.rb', line 399

def initialize_copy(other)
  %{
    self.encoding = other.encoding;
    self.internal_encoding = other.internal_encoding;
  }
end

#inspectObject



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
# File 'opal/opal/corelib/string.rb', line 629

def inspect
  %x{
    var escapable = /[\\\"\x00-\x1f\u007F-\u009F\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        meta = {
          '\u0007': '\\a',
          '\u001b': '\\e',
          '\b': '\\b',
          '\t': '\\t',
          '\n': '\\n',
          '\f': '\\f',
          '\r': '\\r',
          '\v': '\\v',
          '"' : '\\"',
          '\\': '\\\\'
        },
        escaped = self.replace(escapable, function (chr) {
          if (meta[chr]) return meta[chr];
          chr = chr.charCodeAt(0);
          if (chr <= 0xff && (self.encoding["$binary?"]() || self.internal_encoding["$binary?"]())) {
            return '\\x' + ('00' + chr.toString(16).toUpperCase()).slice(-2);
          } else {
            return '\\u' + ('0000' + chr.toString(16).toUpperCase()).slice(-4);
          }
        });
    return '"' + escaped.replace(/\#[\$\@\{]/g, '\\$&') + '"';
  }
end

#instance_variablesObject



1829
1830
1831
# File 'opal/opal/corelib/string.rb', line 1829

def instance_variables
  []
end

#internObject Also known as: to_sym



657
658
659
# File 'opal/opal/corelib/string.rb', line 657

def intern
  `self.toString()`
end

#lengthObject Also known as: size



406
407
408
# File 'opal/opal/corelib/string/encoding.rb', line 406

def length
  `self.length`
end

#lines(separator = $/, &block) ⇒ Object



661
662
663
664
# File 'opal/opal/corelib/string.rb', line 661

def lines(separator = $/, &block)
  e = each_line(separator, &block)
  block ? self : e.to_a
end

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



666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
# File 'opal/opal/corelib/string.rb', line 666

def ljust(width, padstr = ' ')
  width  = `$coerce_to(#{width}, #{Integer}, 'to_int')`
  padstr = `$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.$$cast(self + result.slice(0, width));
  }
end

#lstripObject



690
691
692
# File 'opal/opal/corelib/string.rb', line 690

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

#lstrip!Object



54
55
56
# File 'opal/opal/corelib/unsupported.rb', line 54

def lstrip!(*)
  raise NotImplementedError, `ERROR` % 'lstrip!'
end

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



702
703
704
705
706
707
708
709
710
711
712
# File 'opal/opal/corelib/string.rb', line 702

def match(pattern, pos = undefined, &block)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = Regexp.new(pattern.to_str)
  end

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

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

#match?(pattern, pos = undefined) ⇒ Boolean

Returns:



714
715
716
717
718
719
720
721
722
723
724
# File 'opal/opal/corelib/string.rb', line 714

def match?(pattern, pos = undefined)
  if String === pattern || pattern.respond_to?(:to_str)
    pattern = Regexp.new(pattern.to_str)
  end

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

  pattern.match?(self, pos)
end

#nextObject Also known as: succ



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
# File 'opal/opal/corelib/string.rb', line 726

def next
  %x{
    var i = self.length;
    if (i === 0) {
      return self.$$cast('');
    }
    var result = self;
    var first_alphanum_char_index = self.search(/[a-zA-Z0-9]/);
    var carry = false;
    var code;
    while (i--) {
      code = self.charCodeAt(i);
      if ((code >= 48 && code <= 57) ||
        (code >= 65 && code <= 90) ||
        (code >= 97 && code <= 122)) {
        switch (code) {
        case 57:
          carry = true;
          code = 48;
          break;
        case 90:
          carry = true;
          code = 65;
          break;
        case 122:
          carry = true;
          code = 97;
          break;
        default:
          carry = false;
          code += 1;
        }
      } else {
        if (first_alphanum_char_index === -1) {
          if (code === 255) {
            carry = true;
            code = 0;
          } else {
            carry = false;
            code += 1;
          }
        } else {
          carry = true;
        }
      }
      result = result.slice(0, i) + String.fromCharCode(code) + result.slice(i + 1);
      if (carry && (i === 0 || i === first_alphanum_char_index)) {
        switch (code) {
        case 65:
          break;
        case 97:
          break;
        default:
          code += 1;
        }
        if (i === 0) {
          result = String.fromCharCode(code) + result;
        } else {
          result = result.slice(0, i) + String.fromCharCode(code) + result.slice(i);
        }
        carry = false;
      }
      if (!carry) {
        break;
      }
    }
    return self.$$cast(result);
  }
end

#next!Object



58
59
60
# File 'opal/opal/corelib/unsupported.rb', line 58

def next!(*)
  raise NotImplementedError, `ERROR` % 'next!'
end

#octObject



796
797
798
799
800
801
802
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
# File 'opal/opal/corelib/string.rb', line 796

def oct
  %x{
    var result,
        string = self,
        radix = 8;

    if (/^\s*_/.test(string)) {
      return 0;
    }

    string = string.replace(/^(\s*[+-]?)(0[bodx]?)(.+)$/i, function (original, head, flag, tail) {
      switch (tail.charAt(0)) {
      case '+':
      case '-':
        return original;
      case '0':
        if (tail.charAt(1) === 'x' && flag === '0x') {
          return original;
        }
      }
      switch (flag) {
      case '0b':
        radix = 2;
        break;
      case '0':
      case '0o':
        radix = 8;
        break;
      case '0d':
        radix = 10;
        break;
      case '0x':
        radix = 16;
        break;
      }
      return head + tail;
    });

    result = parseInt(string.replace(/_(?!_)/g, ''), radix);
    return isNaN(result) ? 0 : result;
  }
end

#ordObject



839
840
841
842
843
844
845
846
847
848
# File 'opal/opal/corelib/string.rb', line 839

def ord
  %x{
    if (typeof self.codePointAt === "function") {
      return self.codePointAt(0);
    }
    else {
      return self.charCodeAt(0);
    }
  }
end

#partition(sep) ⇒ Object



850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
# File 'opal/opal/corelib/string.rb', line 850

def partition(sep)
  %x{
    var i, m;

    if (sep.$$is_regexp) {
      m = sep.exec(self);
      if (m === null) {
        i = -1;
      } else {
        #{MatchData.new `sep`, `m`};
        sep = m[0];
        i = m.index;
      }
    } else {
      sep = $coerce_to(sep, #{String}, 'to_str');
      i = self.indexOf(sep);
    }

    if (i === -1) {
      return [self, '', ''];
    }

    return [
      self.slice(0, i),
      self.slice(i, i + sep.length),
      self.slice(i + sep.length)
    ];
  }
end

#prependObject



102
103
104
# File 'opal/opal/corelib/unsupported.rb', line 102

def prepend(*)
  raise NotImplementedError, `ERROR` % 'prepend'
end

#reverseObject



880
881
882
# File 'opal/opal/corelib/string.rb', line 880

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

#reverse!Object



62
63
64
# File 'opal/opal/corelib/unsupported.rb', line 62

def reverse!(*)
  raise NotImplementedError, `ERROR` % 'reverse!'
end

#rindex(search, offset = undefined) ⇒ Object



884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'opal/opal/corelib/string.rb', line 884

def rindex(search, offset = undefined)
  %x{
    var i, m, r, _m;

    if (offset === undefined) {
      offset = self.length;
    } else {
      offset = $coerce_to(offset, #{Integer}, 'to_int');
      if (offset < 0) {
        offset += self.length;
        if (offset < 0) {
          return nil;
        }
      }
    }

    if (search.$$is_regexp) {
      m = null;
      r = Opal.global_multiline_regexp(search);
      while (true) {
        _m = r.exec(self);
        if (_m === null || _m.index > offset) {
          break;
        }
        m = _m;
        r.lastIndex = m.index + 1;
      }
      if (m === null) {
        #{$~ = nil}
        i = -1;
      } else {
        #{MatchData.new `r`, `m`};
        i = m.index;
      }
    } else {
      search = $coerce_to(search, #{String}, 'to_str');
      i = self.lastIndexOf(search, offset);
    }

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

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



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
# File 'opal/opal/corelib/string.rb', line 927

def rjust(width, padstr = ' ')
  width  = `$coerce_to(#{width}, #{Integer}, 'to_int')`
  padstr = `$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 self.$$cast(result + padstr.slice(0, remaining) + self);
  }
end

#rpartition(sep) ⇒ Object



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
# File 'opal/opal/corelib/string.rb', line 947

def rpartition(sep)
  %x{
    var i, m, r, _m;

    if (sep.$$is_regexp) {
      m = null;
      r = Opal.global_multiline_regexp(sep);

      while (true) {
        _m = r.exec(self);
        if (_m === null) {
          break;
        }
        m = _m;
        r.lastIndex = m.index + 1;
      }

      if (m === null) {
        i = -1;
      } else {
        #{MatchData.new `r`, `m`};
        sep = m[0];
        i = m.index;
      }

    } else {
      sep = $coerce_to(sep, #{String}, 'to_str');
      i = self.lastIndexOf(sep);
    }

    if (i === -1) {
      return ['', '', self];
    }

    return [
      self.slice(0, i),
      self.slice(i, i + sep.length),
      self.slice(i + sep.length)
    ];
  }
end

#rstripObject



989
990
991
# File 'opal/opal/corelib/string.rb', line 989

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

#scan(pattern, &block) ⇒ Object



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
# File 'opal/opal/corelib/string.rb', line 993

def scan(pattern, &block)
  %x{
    var result = [],
        match_data = nil,
        match;

    if (pattern.$$is_regexp) {
      pattern = Opal.global_multiline_regexp(pattern);
    } else {
      pattern = $coerce_to(pattern, #{String}, 'to_str');
      pattern = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gm');
    }

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

    #{$~ = `match_data`}

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

#slice!Object



66
67
68
# File 'opal/opal/corelib/unsupported.rb', line 66

def slice!(*)
  raise NotImplementedError, `ERROR` % 'slice!'
end

#split(pattern = undefined, limit = undefined) ⇒ Object



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
1075
1076
1077
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
# File 'opal/opal/corelib/string.rb', line 1026

def split(pattern = undefined, limit = undefined)
  %x{
    if (self.length === 0) {
      return [];
    }

    if (limit === undefined) {
      limit = 0;
    } else {
      limit = #{Opal.coerce_to!(limit, Integer, :to_int)};
      if (limit === 1) {
        return [self];
      }
    }

    if (pattern === undefined || pattern === nil) {
      pattern = #{$; || ' '};
    }

    var result = [],
        string = self.toString(),
        index = 0,
        match,
        i, ii;

    if (pattern.$$is_regexp) {
      pattern = Opal.global_multiline_regexp(pattern);
    } else {
      pattern = $coerce_to(pattern, #{String}, 'to_str').$to_s();
      if (pattern === ' ') {
        pattern = /\s+/gm;
        string = string.replace(/^\s+/, '');
      } else {
        pattern = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gm');
      }
    }

    result = string.split(pattern);

    if (result.length === 1 && result[0] === string) {
      return [self.$$cast(result[0])];
    }

    while ((i = result.indexOf(undefined)) !== -1) {
      result.splice(i, 1);
    }

    function castResult() {
      for (i = 0; i < result.length; i++) {
        result[i] = self.$$cast(result[i]);
      }
    }

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

    match = pattern.exec(string);

    if (limit < 0) {
      if (match !== null && match[0] === '' && pattern.source.indexOf('(?=') === -1) {
        for (i = 0, ii = match.length; i < ii; i++) {
          result.push('');
        }
      }
      castResult();
      return result;
    }

    if (match !== null && match[0] === '') {
      result.splice(limit - 1, result.length - 1, result.slice(limit - 1).join(''));
      castResult();
      return result;
    }

    if (limit >= result.length) {
      castResult();
      return result;
    }

    i = 0;
    while (match !== null) {
      i++;
      index = pattern.lastIndex;
      if (i + 1 === limit) {
        break;
      }
      match = pattern.exec(string);
    }
    result.splice(limit - 1, result.length - 1, string.slice(index));
    castResult();
    return result;
  }
end

#squeeze(*sets) ⇒ Object



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
# File 'opal/opal/corelib/string.rb', line 1125

def squeeze(*sets)
  %x{
    if (sets.length === 0) {
      return self.$$cast(self.replace(/(.)\1+/g, '$1'));
    }
    var char_class = char_class_from_char_sets(sets);
    if (char_class === null) {
      return self;
    }
    return self.$$cast(self.replace(new RegExp('(' + char_class + ')\\1+', 'g'), '$1'));
  }
end

#squeeze!Object



70
71
72
# File 'opal/opal/corelib/unsupported.rb', line 70

def squeeze!(*)
  raise NotImplementedError, `ERROR` % 'squeeze!'
end

#start_with?(*prefixes) ⇒ Boolean

Returns:



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
# File 'opal/opal/corelib/string.rb', line 1138

def start_with?(*prefixes)
  %x{
    for (var i = 0, length = prefixes.length; i < length; i++) {
      if (prefixes[i].$$is_regexp) {
        var regexp = prefixes[i];
        var match = regexp.exec(self);

        if (match != null && match.index === 0) {
          #{$~ = MatchData.new(`regexp`, `match`)};
          return true;
        } else {
          #{$~ = nil}
        }
      } else {
        var prefix = $coerce_to(prefixes[i], #{String}, 'to_str').$to_s();

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

    return false;
  }
end

#stripObject



1164
1165
1166
# File 'opal/opal/corelib/string.rb', line 1164

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

#strip!Object



74
75
76
# File 'opal/opal/corelib/unsupported.rb', line 74

def strip!(*)
  raise NotImplementedError, `ERROR` % 'strip!'
end

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



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
# File 'opal/opal/corelib/string.rb', line 1168

def sub(pattern, replacement = undefined, &block)
  %x{
    if (!pattern.$$is_regexp) {
      pattern = $coerce_to(pattern, #{String}, 'to_str');
      pattern = new RegExp(pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
    }

    var result, match = pattern.exec(self);

    if (match === null) {
      #{$~ = nil}
      result = self.toString();
    } else {
      #{MatchData.new `pattern`, `match`}

      if (replacement === undefined) {

        if (block === nil) {
          #{raise ArgumentError, 'wrong number of arguments (1 for 2)'}
        }
        result = self.slice(0, match.index) + block(match[0]) + self.slice(match.index + match[0].length);

      } else if (replacement.$$is_hash) {

        result = self.slice(0, match.index) + #{`replacement`[`match[0]`].to_s} + self.slice(match.index + match[0].length);

      } else {

        replacement = $coerce_to(replacement, #{String}, 'to_str');

        replacement = replacement.replace(/([\\]+)([0-9+&`'])/g, function (original, slashes, command) {
          if (slashes.length % 2 === 0) {
            return original;
          }
          switch (command) {
          case "+":
            for (var i = match.length - 1; i > 0; i--) {
              if (match[i] !== undefined) {
                return slashes.slice(1) + match[i];
              }
            }
            return '';
          case "&": return slashes.slice(1) + match[0];
          case "`": return slashes.slice(1) + self.slice(0, match.index);
          case "'": return slashes.slice(1) + self.slice(match.index + match[0].length);
          default:  return slashes.slice(1) + (match[command] || '');
          }
        }).replace(/\\\\/g, '\\');

        result = self.slice(0, match.index) + replacement + self.slice(match.index + match[0].length);
      }
    }

    return self.$$cast(result);
  }
end

#sub!Object



78
79
80
# File 'opal/opal/corelib/unsupported.rb', line 78

def sub!(*)
  raise NotImplementedError, `ERROR` % 'sub!'
end

#succ!Object



82
83
84
# File 'opal/opal/corelib/unsupported.rb', line 82

def succ!(*)
  raise NotImplementedError, `ERROR` % 'succ!'
end

#sum(n = 16) ⇒ Object



1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
# File 'opal/opal/corelib/string.rb', line 1227

def sum(n = 16)
  %x{
    n = $coerce_to(n, #{Integer}, 'to_int');

    var result = 0,
        length = self.length,
        i = 0;

    for (; i < length; i++) {
      result += self.charCodeAt(i);
    }

    if (n <= 0) {
      return result;
    }

    return result & (Math.pow(2, n) - 1);
  }
end

#swapcaseObject



1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
# File 'opal/opal/corelib/string.rb', line 1247

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

#swapcase!Object



86
87
88
# File 'opal/opal/corelib/unsupported.rb', line 86

def swapcase!(*)
  raise NotImplementedError, `ERROR` % 'swapcase!'
end

#to_cObject



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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
# File 'opal/opal/corelib/complex.rb', line 307

def to_c
  %x{
    var str = self,
        re = /[+-]?[\d_]+(\.[\d_]+)?(e\d+)?/,
        match = str.match(re),
        real, imag, denominator;

    function isFloat() {
      return re.test(str);
    }

    function cutFloat() {
      var match = str.match(re);
      var number = match[0];
      str = str.slice(number.length);
      return number.replace(/_/g, '');
    }

    // handles both floats and rationals
    function cutNumber() {
      if (isFloat()) {
        var numerator = parseFloat(cutFloat());

        if (str[0] === '/') {
          // rational real part
          str = str.slice(1);

          if (isFloat()) {
            var denominator = parseFloat(cutFloat());
            return #{Rational(`numerator`, `denominator`)};
          } else {
            // reverting '/'
            str = '/' + str;
            return numerator;
          }
        } else {
          // float real part, no denominator
          return numerator;
        }
      } else {
        return null;
      }
    }

    real = cutNumber();

    if (!real) {
      if (str[0] === 'i') {
        // i => Complex(0, 1)
        return #{Complex(0, 1)};
      }
      if (str[0] === '-' && str[1] === 'i') {
        // -i => Complex(0, -1)
        return #{Complex(0, -1)};
      }
      if (str[0] === '+' && str[1] === 'i') {
        // +i => Complex(0, 1)
        return #{Complex(0, 1)};
      }
      // anything => Complex(0, 0)
      return #{Complex(0, 0)};
    }

    imag = cutNumber();
    if (!imag) {
      if (str[0] === 'i') {
        // 3i => Complex(0, 3)
        return #{Complex(0, `real`)};
      } else {
        // 3 => Complex(3, 0)
        return #{Complex(`real`, 0)};
      }
    } else {
      // 3+2i => Complex(3, 2)
      return #{Complex(`real`, `imag`)};
    }
  }
end

#to_fObject



1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'opal/opal/corelib/string.rb', line 1261

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



1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
# File 'opal/opal/corelib/string.rb', line 1278

def to_i(base = 10)
  %x{
    var result,
        string = self.toLowerCase(),
        radix = $coerce_to(base, #{Integer}, 'to_int');

    if (radix === 1 || radix < 0 || radix > 36) {
      #{raise ArgumentError, "invalid radix #{`radix`}"}
    }

    if (/^\s*_/.test(string)) {
      return 0;
    }

    string = string.replace(/^(\s*[+-]?)(0[bodx]?)(.+)$/, function (original, head, flag, tail) {
      switch (tail.charAt(0)) {
      case '+':
      case '-':
        return original;
      case '0':
        if (tail.charAt(1) === 'x' && flag === '0x' && (radix === 0 || radix === 16)) {
          return original;
        }
      }
      switch (flag) {
      case '0b':
        if (radix === 0 || radix === 2) {
          radix = 2;
          return head + tail;
        }
        break;
      case '0':
      case '0o':
        if (radix === 0 || radix === 8) {
          radix = 8;
          return head + tail;
        }
        break;
      case '0d':
        if (radix === 0 || radix === 10) {
          radix = 10;
          return head + tail;
        }
        break;
      case '0x':
        if (radix === 0 || radix === 16) {
          radix = 16;
          return head + tail;
        }
        break;
      }
      return original
    });

    result = parseInt(string.replace(/_(?!_)/g, ''), radix);
    return isNaN(result) ? 0 : result;
  }
end

#to_procObject



1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
# File 'opal/opal/corelib/string.rb', line 1337

def to_proc
  method_name = '$' + `self.valueOf()`

  proc do |*args, &block|
    %x{
      if (args.length === 0) {
        #{raise ArgumentError, 'no receiver given'}
      }

      var recv = args[0];

      if (recv == null) recv = nil;

      var body = recv[#{method_name}];

      if (!body) {
        return recv.$method_missing.apply(recv, args);
      }

      if (typeof block === 'function') {
        body.$$p = block;
      }

      if (args.length === 1) {
        return body.call(recv);
      } else {
        return body.apply(recv, args.slice(1));
      }
    }
  end
end

#to_rObject



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
# File 'opal/opal/corelib/rational.rb', line 362

def to_r
  %x{
    var str = self.trimLeft(),
        re = /^[+-]?[\d_]+(\.[\d_]+)?/,
        match = str.match(re),
        numerator, denominator;

    function isFloat() {
      return re.test(str);
    }

    function cutFloat() {
      var match = str.match(re);
      var number = match[0];
      str = str.slice(number.length);
      return number.replace(/_/g, '');
    }

    if (isFloat()) {
      numerator = parseFloat(cutFloat());

      if (str[0] === '/') {
        // rational real part
        str = str.slice(1);

        if (isFloat()) {
          denominator = parseFloat(cutFloat());
          return #{Rational(`numerator`, `denominator`)};
        } else {
          return #{Rational(`numerator`, 1)};
        }
      } else {
        return #{Rational(`numerator`, 1)};
      }
    } else {
      return #{Rational(0, 1)};
    }
  }
end

#to_sObject Also known as: to_str



1369
1370
1371
# File 'opal/opal/corelib/string.rb', line 1369

def to_s
  `self.toString()`
end

#tr(from, to) ⇒ Object



1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
# File 'opal/opal/corelib/string.rb', line 1377

def tr(from, to)
  %x{
    from = $coerce_to(from, #{String}, 'to_str').$to_s();
    to = $coerce_to(to, #{String}, 'to_str').$to_s();

    if (from.length == 0 || from === to) {
      return self;
    }

    var i, in_range, c, ch, start, end, length;
    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] === '^' && from_chars.length > 1) {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    in_range = false;
    for (i = 0; i < from_length; i++) {
      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) {
        start = last_from.charCodeAt(0);
        end = ch.charCodeAt(0);
        if (start > end) {
          #{raise ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"}
        }
        for (c = start + 1; 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 (i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        in_range = false;
        for (i = 0; i < to_length; i++) {
          ch = to_chars[i];
          if (last_to == null) {
            last_to = 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) {
            start = last_to.charCodeAt(0);
            end = ch.charCodeAt(0);
            if (start > end) {
              #{raise ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"}
            }
            for (c = start + 1; c < end; c++) {
              to_chars_expanded.push(String.fromCharCode(c));
            }
            to_chars_expanded.push(ch);
            in_range = null;
            last_to = 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 (i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

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

    var new_str = ''
    for (i = 0, length = self.length; i < length; i++) {
      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 self.$$cast(new_str);
  }
end

#tr!Object



90
91
92
# File 'opal/opal/corelib/unsupported.rb', line 90

def tr!(*)
  raise NotImplementedError, `ERROR` % 'tr!'
end

#tr_s(from, to) ⇒ Object



1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
# File 'opal/opal/corelib/string.rb', line 1522

def tr_s(from, to)
  %x{
    from = $coerce_to(from, #{String}, 'to_str').$to_s();
    to = $coerce_to(to, #{String}, 'to_str').$to_s();

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

    var i, in_range, c, ch, start, end, length;
    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] === '^' && from_chars.length > 1) {
      inverse = true;
      from_chars.shift();
      global_sub = to_chars[to_length - 1]
      from_length -= 1;
    }

    var from_chars_expanded = [];
    var last_from = null;
    in_range = false;
    for (i = 0; i < from_length; i++) {
      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) {
        start = last_from.charCodeAt(0);
        end = ch.charCodeAt(0);
        if (start > end) {
          #{raise ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"}
        }
        for (c = start + 1; 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 (i = 0; i < from_length; i++) {
        subs[from_chars[i]] = true;
      }
    }
    else {
      if (to_length > 0) {
        var to_chars_expanded = [];
        var last_to = null;
        in_range = false;
        for (i = 0; i < to_length; i++) {
          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) {
            start = last_from.charCodeAt(0);
            end = ch.charCodeAt(0);
            if (start > end) {
              #{raise ArgumentError, "invalid range \"#{`String.fromCharCode(start)`}-#{`String.fromCharCode(end)`}\" in string transliteration"}
            }
            for (c = start + 1; 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 (i = 0; i < length_diff; i++) {
          to_chars.push(pad_char);
        }
      }

      for (i = 0; i < from_length; i++) {
        subs[from_chars[i]] = to_chars[i];
      }
    }
    var new_str = ''
    var last_substitute = null
    for (i = 0, length = self.length; i < length; i++) {
      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 self.$$cast(new_str);
  }
end

#tr_s!Object



94
95
96
# File 'opal/opal/corelib/unsupported.rb', line 94

def tr_s!(*)
  raise NotImplementedError, `ERROR` % 'tr_s!'
end

#unicode_normalize(form = :nfc) ⇒ Object

Raises:



1837
1838
1839
1840
# File 'opal/opal/corelib/string.rb', line 1837

def unicode_normalize(form = :nfc)
  raise ArgumentError, "Invalid normalization form #{form}" unless %i[nfc nfd nfkc nfkd].include?(form)
  `self.normalize(#{form.upcase})`
end

#unicode_normalize!Object



118
119
120
# File 'opal/opal/corelib/unsupported.rb', line 118

def unicode_normalize!(*)
  raise NotImplementedError, `ERROR` % 'unicode_normalize!'
end

#unicode_normalized?(form = :nfc) ⇒ Boolean

Returns:



1842
1843
1844
# File 'opal/opal/corelib/string.rb', line 1842

def unicode_normalized?(form = :nfc)
  unicode_normalize(form) == self
end

#unpack(format) ⇒ Object



1846
1847
1848
# File 'opal/opal/corelib/string.rb', line 1846

def unpack(format)
  raise "To use String#unpack, you must first require 'corelib/string/unpack'."
end

#unpack1(format) ⇒ Object



1850
1851
1852
# File 'opal/opal/corelib/string.rb', line 1850

def unpack1(format)
  raise "To use String#unpack1, you must first require 'corelib/string/unpack'."
end

#upcaseObject



1685
1686
1687
# File 'opal/opal/corelib/string.rb', line 1685

def upcase
  `self.$$cast(self.toUpperCase())`
end

#upcase!Object



98
99
100
# File 'opal/opal/corelib/unsupported.rb', line 98

def upcase!(*)
  raise NotImplementedError, `ERROR` % 'upcase!'
end

#upto(stop, excl = false, &block) ⇒ Object



1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
# File 'opal/opal/corelib/string.rb', line 1689

def upto(stop, excl = false, &block)
  return enum_for :upto, stop, excl unless block_given?
  %x{
    var a, b, s = self.toString();

    stop = $coerce_to(stop, #{String}, 'to_str');

    if (s.length === 1 && stop.length === 1) {

      a = s.charCodeAt(0);
      b = stop.charCodeAt(0);

      while (a <= b) {
        if (excl && a === b) {
          break;
        }

        block(String.fromCharCode(a));

        a += 1;
      }

    } else if (parseInt(s, 10).toString() === s && parseInt(stop, 10).toString() === stop) {

      a = parseInt(s, 10);
      b = parseInt(stop, 10);

      while (a <= b) {
        if (excl && a === b) {
          break;
        }

        block(a.toString());

        a += 1;
      }

    } else {

      while (s.length <= stop.length && s <= stop) {
        if (excl && s === stop) {
          break;
        }

        block(s);

        s = #{`s`.succ};
      }

    }
    return self;
  }
end

#valid_encoding?Boolean

stub

Returns:



413
414
415
# File 'opal/opal/corelib/string/encoding.rb', line 413

def valid_encoding?
  true
end