tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

string-totitlecase.js (2009B)


      1 // Test inline title case conversion.
      2 
      3 function* characters(...ranges) {
      4  for (let [start, end] of ranges) {
      5    for (let i = start; i <= end; ++i) {
      6      yield i;
      7    }
      8  }
      9 }
     10 
     11 const ascii = [...characters(
     12  [0x41, 0x5A], // A..Z
     13  [0x61, 0x7A], // a..z
     14  [0x30, 0x39], // 0..9
     15 )];
     16 
     17 const latin1 = [...characters(
     18  [0xC0, 0xFF], // À..ÿ
     19 )];
     20 
     21 const twoByte = [...characters(
     22  [0x100, 0x17E], // Ā..ž
     23 )];
     24 
     25 String.prototype.toTitleCase = function() {
     26  "use strict";
     27 
     28  var s = String(this);
     29 
     30  if (s.length === 0) {
     31    return s;
     32  }
     33  return s[0].toUpperCase() + s.substring(1);
     34 };
     35 
     36 function toRope(s) {
     37  try {
     38    return newRope(s[0], s.substring(1));
     39  } catch {}
     40  // newRope can fail when |s| fits into an inline string. In that case simply
     41  // return the input.
     42  return s;
     43 }
     44 
     45 for (let i = 0; i <= 32; ++i) {
     46  let strings = [ascii, latin1, twoByte].flatMap(codePoints => [
     47    String.fromCodePoint(...codePoints.slice(0, i)),
     48 
     49    // Leading ASCII upper case character.
     50    "A" + String.fromCodePoint(...codePoints.slice(0, i)),
     51 
     52    // Leading ASCII lower case character.
     53    "a" + String.fromCodePoint(...codePoints.slice(0, i)),
     54 
     55    // Leading Latin-1 upper case character.
     56    "À" + String.fromCodePoint(...codePoints.slice(0, i)),
     57 
     58    // Leading Latin-1 lower case character.
     59    "à" + String.fromCodePoint(...codePoints.slice(0, i)),
     60 
     61    // Leading Two-Byte upper case character.
     62    "Ā" + String.fromCodePoint(...codePoints.slice(0, i)),
     63 
     64    // Leading Two-Byte lower case character.
     65    "ā" + String.fromCodePoint(...codePoints.slice(0, i)),
     66  ]).flatMap(x => [
     67    x,
     68    toRope(x),
     69    newString(x, {twoByte: true}),
     70  ]);
     71 
     72  const expected = strings.map(x => {
     73    // Prevent Warp compilation when computing the expected results.
     74    with ({}) ;
     75    return x.toTitleCase();
     76  });
     77 
     78  for (let i = 0; i < 1000; ++i) {
     79    let idx = i % strings.length;
     80    let str = strings[idx];
     81 
     82    let actual = str.toTitleCase();
     83    if (actual !== expected[idx]) throw new Error();
     84  }
     85 }