Skip to content

Instantly share code, notes, and snippets.

@rolandoam
Created November 24, 2012 19:25
Show Gist options
  • Save rolandoam/4141093 to your computer and use it in GitHub Desktop.
Save rolandoam/4141093 to your computer and use it in GitHub Desktop.
compare two spanish words
var spanishCharsMap = {
225: 97, // á
233: 101, // é
237: 105, // í
243: 111, // ó
250: 117, // ú
241: 110 // ñ
};
/**
* This only works for lowercase words. Not the most efficient way, but it works consistently
* across browsers, and it should also work on ascii-only languages (english for instance)
* @param {string} worda
* @param {string} wordb
* @return {number} returns -1, 0, 1 if worda is lower, equal or greater than wordb in the
* lexicographic order
*/
var spanishCompare = function (worda, wordb) {
var len = Math.min(worda.length, wordb.length),
i;
for (i=0; i < len; i++) {
var a = worda.charCodeAt(i),
b = wordb.charCodeAt(i);
if (a === b)
continue;
// regular characters
if (a >= 97 && a <= 122 && b >= 97 && b <= 122)
return (a < b ? -1 : 1);
if (a > 200 || b > 200) {
var mappedA = spanishCharsMap[a] || a,
mappedB = spanishCharsMap[b] || b;
if (mappedA == mappedB) {
return (a > b ? 1 : -1);
}
return (mappedA > mappedB ? 1 : -1);
}
throw "invalid character range: " + [a,b].join(",") + " (testing " + worda + " vs " + wordb + ")";
}
// they're equal
if (worda.length == wordb.length)
return 0;
// one is larger than the other
return (worda.length < wordb.length ? -1 : 1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment