JavaScriptFundamental (ES6), part 2
Reverse a string safely with spread in JavaScript
100 Reversing a string without breaking the emoji
fairReverse a string. Do it with split('') and again with [...str], and compare the two on a string containing an emoji. Then push the spread version until it breaks too: a flag, and a name written with a combining accent.
Stuck? Three hints, smallest first
- 1.
split('')splits into UTF-16 code units, and an emoji is two of them. - 2. The iterator behind spread and
Array.fromwalks whole code points, so the pair stays together. - 3. A code point is still not a character: a flag is two code points, and a combining accent is a code point of its own.
const reverseByUnit = (text) => text.split('').reverse().join('');
const reverseByCodePoint = (text) => [...text].reverse().join('');
const plain = 'Lagos';
const withEmoji = 'Lagos \u{1F389}'; // a party popper, one code point, two code units
const bothAgreeOnAscii = [reverseByUnit(plain), reverseByCodePoint(plain)];
const unitLength = withEmoji.length;
const pointLength = [...withEmoji].length;
const arrayFromIsTheSame = reverseByCodePoint(withEmoji) === Array.from(withEmoji).reverse().join('');
const brokenByUnits = reverseByUnit(withEmoji).includes('\u{1F389}');
const keptByCodePoints = reverseByCodePoint(withEmoji);
// A flag is two regional-indicator code points, so reversing them is legal and wrong.
const nigeria = '\u{1F1F3}\u{1F1EC}';
const flagPoints = [...nigeria].length;
const reversedFlag = reverseByCodePoint(nigeria);
const becameGuinea = reversedFlag === '\u{1F1EC}\u{1F1F3}';
// A combining accent is its own code point, and it attaches to whatever precedes it.
const composed = 'Ad\u00e9';
const decomposed = 'Ade\u0301';
const reversedComposed = reverseByCodePoint(composed);
const reversedDecomposed = reverseByCodePoint(decomposed);
const twiceIsIdentity = reverseByCodePoint(reverseByCodePoint(withEmoji)) === withEmoji;
console.log('by code unit :', reverseByUnit(withEmoji), '<- the emoji is in pieces');
console.log('by code point:', keptByCodePoints);
console.log('the flag :', nigeria, '->', reversedFlag);
console.log('the accent :', decomposed, '->', JSON.stringify(reversedDecomposed));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('on plain ASCII the two versions are indistinguishable', bothAgreeOnAscii, ['sogaL', 'sogaL']);
test('length counts code units while spread counts code points, so they disagree', [unitLength, pointLength], [8, 7]);
test('splitting by code unit tears the surrogate pair apart and loses the emoji', brokenByUnits, false);
test('spreading keeps it whole, and Array.from does exactly the same thing', [keptByCodePoints, arrayFromIsTheSame], ['\u{1F389} sogaL', true]);
test('reversing twice by code point gets the original back', twiceIsIdentity, true);
test('but a flag is two code points, so reversing it names a different country', [flagPoints, becameGuinea], [2, true]);
test('and a precomposed accent survives while a decomposed one lands on nothing', [reversedComposed, reversedDecomposed], ['\u00e9dA', '\u0301edA']);
test('which is why normalising to NFC first is part of the job', reverseByCodePoint(decomposed.normalize('NFC')), '\u00e9dA');
split('') splits into UTF-16 code units, and every emoji above U+FFFF is stored as two of them — a surrogate pair. Reversing the units swaps the pair, and the result is two lone surrogates that no longer name a character at all, which is where the black diamonds in a reversed string come from. Spread and Array.from use the string iterator, which yields whole code points, so the pair travels as one unit. That is the fix worth remembering, and [...str].length is the honest character count in the same way.
Then the harder truth: a code point is still not a character. The sixth assertion reverses the Nigerian flag into Guinea's, because a flag is two regional indicator letters — NG becomes GN — and both are perfectly valid. Skin-tone modifiers, ZWJ sequences like a family emoji, and Devanagari vowel signs all break the same way. The seventh is the same problem in a customer's name: a combining accent applies to the character before it, so reversing puts it on the wrong letter, or on nothing.
The unit that actually matters is the grapheme cluster, and computing it needs the Unicode segmentation rules — Intl.Segmenter with granularity: 'grapheme' in a modern runtime, or a library. Deliberately not used here: the point of the exercise is that [...str] is a real improvement over split('') and still not the last word. Normalising to NFC first, as the last assertion does, covers the accent case cheaply and leaves the flags alone.