Created
April 2, 2014 22:03
-
-
Save travellingprog/9944155 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var locationSorter = function(a, b) { | |
// this sorts letters before numbers on the 1st character, and also | |
// sorts something like "1C9" before "1C11" | |
var n = (a.name || "").toLowerCase(); | |
var m = (b.name || "").toLowerCase(); | |
var l = Math.min(n.length, m.length); | |
if (n.substr(0, l) === m.substr(0,l)) { | |
return (n.length - m.length); | |
} | |
for (var i = 0; i < l; i++) { | |
var nChar = n.charCodeAt(i); | |
var mChar = m.charCodeAt(i); | |
var nCharIsDigit = (nChar >= 48 && nChar <= 57); | |
var mCharIsDigit = (mChar >= 48 && mChar <= 57); | |
var nCharIsLetter = (nChar >= 97 && nChar <= 122); | |
var mCharIsLetter = (mChar >= 97 && mChar <= 122); | |
if (i === 0) { | |
// for 1st character, letters are sorted before numbers | |
if (nCharIsDigit && mCharIsLetter) { | |
return 1; | |
} | |
if (nCharIsLetter && mCharIsDigit) { | |
return -1; | |
} | |
} | |
else if (i > 0 && nCharIsDigit && mCharIsDigit) { | |
// Compare numerical values | |
var numberComparison = parseInt(n.substr(i), 10) - parseInt(m.substr(i), 10); | |
if (numberComparison !== 0) return numberComparison; | |
// note: if numberComparison = 0, we might be comparing something like "1CD" and "1FF", | |
// so check the next character instead | |
} | |
if (nChar !== mChar) { | |
return nChar - mChar; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment