Created
July 28, 2016 12:09
-
-
Save bj7/ba4625440fda82a314d5fdaed4eb1c50 to your computer and use it in GitHub Desktop.
This is an alphanumeric less than evaluator. It works on strings and numbers passed as arguments. When evaluating alphanumeric strings (string-1, string-2), it tests the string portion for equality, and if equal begins testing the numeric portion at the end.
This file contains 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
/** | |
* Routine to compare numbers or strings and combinations thereof in terms | |
* of string1 < string2 | |
* | |
* @param {Number|String} string1 First item to compare | |
* @param {Number|String} string2 Second item to compare | |
* @return {Boolean} True if string1 < string2, else false. | |
*/ | |
var lessThan = function(string1, string2) { | |
// handle generic numbers | |
if (typeof (string1) === 'number' && typeof (string2) === 'number') { | |
return string1 < string2; | |
} | |
// else we need to compare some strings! | |
string1 = string1.toLowerCase(); | |
string2 = string2.toLowerCase(); | |
// only match if at the end of string, eg. item, item-1, item-2, etc. | |
var regex = /([0-9]+)$/g; | |
var alpha1 = string1.split(regex); | |
var num1 = string1.match(regex); | |
var alpha2 = string2.split(regex); | |
var num2 = string2.match(regex); | |
// if there are no numerical parts to our strings, simply return the | |
// result | |
if (num1 === null && num2 === null) { | |
return (string1 < string2); | |
} | |
// else we need to test these strings | |
// total the numeric portions | |
var total1 = 0; | |
if (num1 !== null) { | |
total1 = parseInt(num1.join(''), 10); | |
} | |
var total2 = 0; | |
if (num2 !== null) { | |
total2 = parseInt(num2.join(''), 10); | |
} | |
if (alpha1[0] == alpha2[0]) { | |
return (total1 < total2); | |
} else { | |
return (alpha1[0] < alpha2[0]); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment