2

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?

3
  • your ternary operator was missing a : so I fixed it, plus I gave your function a name. Commented Oct 22, 2012 at 23:48
  • Did you see my comment on the built in method is not faster? Just because it is part of the "language" does not mean it is "better". Commented Oct 23, 2012 at 1:06
  • possible duplicate of Is there a JavaScript strcmp()? Commented Aug 16, 2013 at 17:25

1 Answer 1

4

Perhaps you should check localeCompare function? That's exactly its purpose: compare the strings. )

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

2 Comments

Yeah, but you wanted faster right? Built in is not always faster. Try it out jsperf.com/looking-at-localcompare
Especially given that localCompare implementations handle a bit more than just what you'd want them to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.