0

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?

4
  • what would be the output of "abc" & "abd"? Commented May 14, 2017 at 15:12
  • Seems overcomplicated? -> jsfiddle.net/adeneo/1w7kudsj Commented May 14, 2017 at 15:15
  • @adeneo Your fiddle returns 1 for strcmp("fooABC", "oabc") Commented May 14, 2017 at 15:25
  • @Barmar - it could return 666 for all I care, it's written for the three examples posted, there's no other explanation of what the function is supposed to do, but if it's only suppose to compare the start of the string, or do so case-sensitive, that result is clearly not correct ? Commented May 14, 2017 at 15:28

2 Answers 2

1

Converting the whole string to lowercase means you have to loop over all the characters, even though the comparison will stop at the first character difference. So if you convert each character as you get to it, you only do as many conversions as you need to get the result. Unless the two strings are equal, you'll always do fewer conversions this way; when they're equal, you do the same number of conversions.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for answering the question.
0

As an answer to your question, it is correct that you saved the lowercase string into a variable. If you would have converted inside the for loop, then on every iteration the toLowerCase() method would have been called called, which is inefficient.

Now, not sure if you know, but javascript has a method similar to strcmp, called localeCompare(). So an alternative to your code would be this:

a.toLowerCase().localeCompare(b.toLowerCase());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.