string-trim.js (1633B)
1 const whitespace = [ 2 // Ascii whitespace 3 " ", 4 "\t", 5 6 // Latin-1 whitespace 7 "\u{a0}", 8 9 // Two-byte whitespace 10 "\u{1680}", 11 ]; 12 13 const strings = [ 14 // Empty string 15 "", 16 17 // Ascii strings 18 "a", 19 "abc", 20 21 // Latin-1 strings 22 "á", 23 "áèô", 24 25 // Two-byte strings 26 "\u{100}", 27 "\u{100}\u{101}\u{102}", 28 ].flatMap(x => [ 29 x, 30 31 // Leading whitespace 32 ...whitespace.flatMap(w => [w + x, w + w + x]), 33 34 // Trailing whitespace 35 ...whitespace.flatMap(w => [x + w, x + w + w]), 36 37 // Leading and trailing whitespace 38 ...whitespace.flatMap(w => [w + x + w, w + w + x + w + w]), 39 40 // Interspersed whitespace 41 ...whitespace.flatMap(w => [x + w + x, x + w + w + x]), 42 ]); 43 44 function trim(strings) { 45 // Compute expected values using RegExp. 46 let expected = strings.map(x => x.replace(/(^\s+)|(\s+$)/g, "")); 47 48 for (let i = 0; i < 1000; ++i) { 49 let index = i % strings.length; 50 assertEq(strings[index].trim(), expected[index]); 51 } 52 } 53 for (let i = 0; i < 2; ++i) trim(strings); 54 55 function trimStart(strings) { 56 // Compute expected values using RegExp. 57 let expected = strings.map(x => x.replace(/(^\s+)/g, "")); 58 59 for (let i = 0; i < 1000; ++i) { 60 let index = i % strings.length; 61 assertEq(strings[index].trimStart(), expected[index]); 62 } 63 } 64 for (let i = 0; i < 2; ++i) trimStart(strings); 65 66 function trimEnd(strings) { 67 // Compute expected values using RegExp. 68 let expected = strings.map(x => x.replace(/(\s+$)/g, "")); 69 70 for (let i = 0; i < 1000; ++i) { 71 let index = i % strings.length; 72 assertEq(strings[index].trimEnd(), expected[index]); 73 } 74 } 75 for (let i = 0; i < 2; ++i) trimEnd(strings);