I’m failing to grasp what the Bitwise module is doing. The documentation doesn’t have much (see for yourself). I have a decent understanding of binary already. Not sure what the &&&
is doing though.
Any explanation to help me understand the following code (just a practice problem off Exercism) would be immensely helpful. I have 2 weeks to get off the ground and start an Elixir project at work so trying to learn as much as I can.
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 = wink
10 = double blink
100 = close your eyes
1000 = jump
10000 = Reverse the order of the operations in the secret handshake
"""
use Bitwise
@spec commands(code :: integer) :: list(String.t())
def commands(code) do
[]
|> handshake(code &&& 0b00001)
|> handshake(code &&& 0b00010)
|> handshake(code &&& 0b00100)
|> handshake(code &&& 0b01000)
|> handshake(code &&& 0b10000)
end
def handshake(list, 0b00001), do: list ++ ["wink"]
def handshake(list, 0b00010), do: list ++ ["double blink"]
def handshake(list, 0b00100), do: list ++ ["close your eyes"]
def handshake(list, 0b01000), do: list ++ ["jump"]
def handshake(list, 0b10000), do: Enum.reverse(list)
def handshake(list, _), do: list
end