DEV Community

Discussion on: Sort a String using a Custom Alphabet in Elixir

lindentree profile image
Linden Chiu • Edited

map = alphabet
|> String.split("", trim: true)
|> Enum.with_index()
|> Enum.reduce(%{}, fn({k,v}, acc)-> Map.put(acc, k, v) end)

You can create this map in the main alphabetize function, so you only have to do it once.
Then you can pass it into compare_alpha(a, b, map), and it becomes just:

map[a] < map[b]

I used a regular string for the alphabet instead of a sigil; I'm not familiar with Elixir, so I didn't know how to pass the indices from the list into the reduce function. (EDIT: Enum.with_index() works on the sigil, so you don't need to split an alphabet string)