21 lines
591 B
Elixir
21 lines
591 B
Elixir
defmodule YouTubeID do
|
|
@youtube_chars "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
|
@base length(String.graphemes(@youtube_chars))
|
|
|
|
def to_integer(<<video_id::binary-size(11)>>) do
|
|
video_id
|
|
|> String.graphemes()
|
|
|> Enum.reverse()
|
|
|> Enum.with_index()
|
|
|> Enum.reduce(0, fn {char, index}, acc ->
|
|
char_value = contains_at(@youtube_chars, char)
|
|
acc + char_value * trunc(:math.pow(@base, index))
|
|
end)
|
|
end
|
|
|
|
defp contains_at(string, char) do
|
|
String.split(string, "", trim: true)
|
|
|> Enum.find_index(&(&1 == char))
|
|
end
|
|
end
|