I have a simple question. I would like to write a string comparer function, which would return a number to indicate whether the first string is less, equal or greater than the second.
Apparently the easiest solution is:
function compare (x, y){
return x < y ? -1 : (x === y ? 0 : 1);
}
However, this is not a very efficient one, because strings may be compared twice. On the other hand, implementing a typical text book solution (iterating over both of the strings and comparing the characters in the respective positions) would probably be even more inefficient, because Javascript has no notion of individual characters - there are 1 character strings instead.
So, is there a trick using some built-in Javascript functionality (ES5, maybe?) to have an efficient implementation of such a function or are we stuck with the aforementioned code?