InscrutableCode: Lexicographic Ordering in Javascript
InscrutableCode is a place where I document particularly nasty broken things that I encounter as a software developer. Partly to inform, mostly as therapy.
In lexicographic ordering (from Wikipedia):
Given two different words of the same length, say a = a1a2...ak and b = b1b2...bk, the order of the two words depends on the alphabetic order of the symbols in the first place i where the two words differ (counting from the beginning of the words): a < b if and only if ai < bi in the underlying order of the alphabet A.
This means that str1 > str2
implies that str1 + prefix1 > str2 + prefix2
, for any prefix1
and prefix2
.
Javascript violates this basic property of string comparison.
'é'.localeCompare('e') // 1 which means é > e
'éa'.localeCompare('eb') // -1 which means éa < eb