The Oddler
The Oddler

Reputation: 6708

Comparing strings to search string?

I have a list of all Pokémon for a little project I'm making. Now I added a search box, in which you can type of Pokémon's name. I would like to sort my list of Pokémon based on the search string.

So for instance, if I search for "bul", I would expect "Bulbasaur" to be at the top, followed by "Snubbull" and "Granbull" (because they also have "bul" in their name), after that for instance "Wobbufet" (because he has "bu" in his name).

What kind of string comparison could I use for this?

Note: I'm working in Elm, so if there is a solution in Elm that would be nice, but the question is mainly just in general.

Upvotes: 2

Views: 705

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

You could build a function that assigns a weight to each item in the list, then sort by that. You could create a function with signature:

assignWeight : String -> String -> (Int, String)
assignWeight typed listItem = ...

This function could then assign a numeric value and return it as the first item of the tuple, with the original value as the second item in the tuple.

Then you just have to build your weighting algorithm, and those rules will have to be decided by your requirements.

For example, you could assign an exact match 100. You could assign partial matches some value that depends on how much of the typed string matches, and how many characters are actually matched. You could use the Regex library for all these scenarios, building up partial regexes with the escape function.

For example, an exact match Regex could be defined as:

exactMatcher typed =
  caseInsensitive <| regex <| "^" ++ escape typed ++ "$"

Whereas a partial match could be:

partialMatcher =
  caseInsensitive << regex << escape

When you use the partialMatcher regex, you could use the returned Match index value to determine how deep into the string the match occurs.

You could even do partial matches on each variation of the typed input (e.g. "bul", "bu", and "b"), and factor that into your weighting score.

At the end of the day, you can use List.sortBy and fst to use your sorting algorithm:

List.sortBy (fst << assignWeight "bu") pokemon

Upvotes: 2

Related Questions