I was tasked with writing a string comparison function, where the result is as follows:
"ABC" & "abc" returns 0;
"abc" & "abcd" return -1;
"abcd" & "abc" returns 1;
My solution was:
function strcmp(a,b){
var aTemp = a.toLowerCase();
var bTemp = b.toLowerCase();
if(aTemp === bTemp){
return 0;
} else {
for(var i = 0; i < aTemp.length;i++){
var charAtA = aTemp.charCodeAt(i), charAtB = bTemp.charCodeAt(i);
if(charAtB !== charAtB) // NaN returns false when compared to itself.
return 1;
if(charAtA < charAtB)
return -1;
else if(charAtA > charAtB)
return 1;
}
if(bTemp.length > aTemp.length)
return -1;
return 0;
}
}
When presenting my solution (besides finding a bug in the code), I was asked why I had converted the strings to lowercase and stored them in a parameter, rather than for each iteration of the for loop, converting the character to lowercase. So my question is, what is the right way to convert a string to lowercase, what is more efficient, or was the person that I submitted the answer to just playing mind games with me?
"abc" & "abd"?strcmp("fooABC", "oabc")