I am trying to optimize a function which does binary search of strings in JavaScript.
Binary search requires you to know whether the key is ==
the pivot or <
the pivot.
But this requires two string comparisons in JavaScript, unlike in C
like languages which have the strcmp()
function that returns three values (-1, 0, +1)
for (less than, equal, greater than).
Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search?
The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.
In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.
To compare two strings in JavaScript, use the localeCompare() method. The method returns 0 if both the strings are equal, -1 if string 1 is sorted before string 2 and 1 if string 2 is sorted before string 1.
Firstly, you are safe to compare strings that contain characters from Basic Multilangual Plane (including the ASCII characters) using regular comparison operators === , == or utility function Object.is() . Both str1 and str2 contain ASCII characters, so you can safely compare them using comparison operators.
You can use the localeCompare()
method.
string_a.localeCompare(string_b); /* Expected Returns: 0: exact match -1: string_a < string_b 1: string_a > string_b */
Further Reading:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With