|
11 | 11 |
|
12 | 12 | const assert = require("chai").assert;
|
13 | 13 |
|
14 |
| -const { upperCaseFirst } = require("../../../lib/shared/string-utils"); |
| 14 | +const { upperCaseFirst, getGraphemeCount } = require("../../../lib/shared/string-utils"); |
| 15 | + |
| 16 | +//------------------------------------------------------------------------------ |
| 17 | +// Helpers |
| 18 | +//------------------------------------------------------------------------------ |
| 19 | + |
| 20 | +/** |
| 21 | + * Replaces raw control characters with the `\xXX` form. |
| 22 | + * @param {string} text The text to process. |
| 23 | + * @returns {string} `text` with escaped control characters. |
| 24 | + */ |
| 25 | +function escapeControlCharacters(text) { |
| 26 | + return text.replace( |
| 27 | + /[\u0000-\u001F\u007F-\u009F]/gu, // eslint-disable-line no-control-regex -- intentionally including control characters |
| 28 | + c => `\\x${c.codePointAt(0).toString(16).padStart(2, "0")}` |
| 29 | + ); |
| 30 | +} |
15 | 31 |
|
16 | 32 | //------------------------------------------------------------------------------
|
17 | 33 | // Tests
|
@@ -39,3 +55,34 @@ describe("upperCaseFirst", () => {
|
39 | 55 | assert(upperCaseFirst("") === "");
|
40 | 56 | });
|
41 | 57 | });
|
| 58 | + |
| 59 | +describe("getGraphemeCount", () => { |
| 60 | + /* eslint-disable quote-props -- Make consistent here for readability */ |
| 61 | + const expectedResults = { |
| 62 | + "": 0, |
| 63 | + "a": 1, |
| 64 | + "ab": 2, |
| 65 | + "aa": 2, |
| 66 | + "123": 3, |
| 67 | + "cccc": 4, |
| 68 | + [Array.from({ length: 128 }, (_, i) => String.fromCharCode(i)).join("")]: 128, // all ASCII characters |
| 69 | + "👍": 1, // 1 grapheme, 1 code point, 2 code units |
| 70 | + "👍👍": 2, |
| 71 | + "👍9👍": 3, |
| 72 | + "a👍b": 3, |
| 73 | + "👶🏽": 1, // 1 grapheme, 2 code points, 4 code units |
| 74 | + "👨👩👦": 1, // 1 grapheme, 5 code points, 8 code units |
| 75 | + "👨👩👦👨👩👦": 2, |
| 76 | + "👨👩👦a👨👩👦": 3, |
| 77 | + "a👨👩👦b👨👩👦c": 5, |
| 78 | + "👨👩👦👍": 2, |
| 79 | + "👶🏽👨👩👦": 2 |
| 80 | + }; |
| 81 | + /* eslint-enable quote-props -- Make consistent here for readability */ |
| 82 | + |
| 83 | + Object.entries(expectedResults).forEach(([key, value]) => { |
| 84 | + it(`should return ${value} for ${escapeControlCharacters(key)}`, () => { |
| 85 | + assert.strictEqual(getGraphemeCount(key), value); |
| 86 | + }); |
| 87 | + }); |
| 88 | +}); |
0 commit comments