exercism/elixir/secret-handshake/lib/secret_handshake.ex

36 lines
867 B
Elixir
Raw Normal View History

2024-03-11 12:03:00 +00:00
defmodule SecretHandshake do
@doc """
Determine the actions of a secret handshake based on the binary
representation of the given `code`.
If the following bits are set, include the corresponding action in your list
of commands, in order from lowest to highest.
1 1 = wink
2 10 = double blink
4 100 = close your eyes
8 1000 = jump
16 10000 = Reverse the order of the operations in the secret handshake
"""
@coms %{
1 => "wink",
2 => "double blink",
4 => "close your eyes",
8 => "jump",
16 => "reverse"
}
@spec commands(code :: integer) :: list(String.t())
def commands(code) do
@coms
|> Map.keys()
|> Enum.reduce([], &if(Bitwise.band(code, &1) == &1, do: [@coms[&1] | &2], else: &2))
|> case do
["reverse" | tail] -> tail
reversed_list -> Enum.reverse(reversed_list)
end
end
end