From dff16e356e2755adca5ed73e9496627fde29c992 Mon Sep 17 00:00:00 2001 From: Eyad Al-Khalidy <41296016+eyad-alkhalidy@users.noreply.github.com> Date: Sun, 1 Jun 2025 18:27:02 +0300 Subject: [PATCH] fix(solution): handle Unicode surrogate pairs in reverseString --- 07_reverseString/solution/reverseString-solution.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/07_reverseString/solution/reverseString-solution.js b/07_reverseString/solution/reverseString-solution.js index 839f32e2838..34651d4db4e 100644 --- a/07_reverseString/solution/reverseString-solution.js +++ b/07_reverseString/solution/reverseString-solution.js @@ -1,5 +1,16 @@ const reverseString = function (string) { - return string.split("").reverse().join(""); + return Array.from(string).reverse().join(""); + + /* + The following statement: `return string.split("").reverse().join("");` + also works but only if the passed string doesn't include any complex Unicode character, + i.e. a characher stored in a surrogate pair, which is a pair of 16-bit code units that represents a single character. + Example: emojis as in "Great 👍" and some accented characters as in "mañana". + + The `split()` method splits the String by UTF-16 code units and will separate surrogate pairs resulting in invalid characters. + + Search about 'Surrogate Pairs' and 'Grapheme Clusters' for more information. + */ }; module.exports = reverseString;