From d2f786adb3aea25bc3e07b5c51af3bb35fe84ab8 Mon Sep 17 00:00:00 2001 From: Eric Morand <156682586+ericmorand-sonarsource@users.noreply.github.com> Date: Wed, 31 Jan 2024 17:27:47 +0100 Subject: [PATCH] Modify rule S2871: Emphasize the necessity of using String.localeCompare to sort arrays of strings (#3576) * Modify rule S2871: Add exception for arrays of strings * S2871: Remove the exception mention and emphasize the usage of String.localeCompare --- rules/S2871/javascript/rule.adoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rules/S2871/javascript/rule.adoc b/rules/S2871/javascript/rule.adoc index b9ecfe60d1..3737326a8a 100644 --- a/rules/S2871/javascript/rule.adoc +++ b/rules/S2871/javascript/rule.adoc @@ -25,7 +25,7 @@ numbers.sort((a, b) => a - b); console.log(numbers); // Output: [1, 2, 5, 10, 30] ---- -Even to sort strings, the default sort order may give unexpected results. Not only does it not support localization, it also doesn't fully support Unicode, as it only considers UTF-16 code units. For example, in the code below, `"eΔ"` is surprisingly before and after `"éΔ"`. +Even to sort strings, the default sort order may give unexpected results. Not only does it not support localization, it also doesn't fully support Unicode, as it only considers UTF-16 code units. For example, in the code below, `"eΔ"` is surprisingly before and after `"éΔ"`. To guarantee that the sorting is reliable and remains as such in the long run, it is necessary to provide a compare function that is both locale and Unicode aware - typically `String.localeCompare`. [source,javascript] ----