Sha256: 12f2dc476742a5f48e90060c9db11285162128a03ae5604788eaa20da8a9bb72

Contents?: true

Size: 814 Bytes

Versions: 69

Compression:

Stored size: 814 Bytes

Contents

defmodule Luhn do
  @doc """
  Checks if the given number is valid via the luhn formula
  """
  @spec valid?(String.t()) :: boolean
  def valid?(number) do
    number_without_spaces = String.replace(number, " ", "")

    case Integer.parse(number_without_spaces) do
      {_, ""} ->
        String.length(number_without_spaces) > 1 && checksum(number_without_spaces)

      _ ->
        false
    end
  end

  defp checksum(number) do
    0 ==
      number
      |> String.graphemes()
      |> Enum.map(&String.to_integer/1)
      |> double_even()
      |> Enum.sum()
      |> rem(10)
  end

  defp double_even(numlist) do
    numlist
    |> Enum.reverse()
    |> Enum.zip(Stream.cycle([1, 2]))
    |> Enum.map(fn {n, m} -> n * m end)
    |> Enum.map(fn
      n when n > 9 -> n - 9
      n -> n
    end)
  end
end

Version data entries

69 entries across 69 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.179 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.178 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.177 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.176 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.175 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.174 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.173 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.172 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.171 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.170 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.169 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.167 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.166 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.165 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.164 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.163 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.162 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.161 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.160 tracks/elixir/exercises/luhn/example.exs