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.159 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.158 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.157 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.156 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.155 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.154 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.153 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.152 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.151 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.150 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.149 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.148 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.147 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.146 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.145 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.144 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.143 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.142 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.141 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.140 tracks/elixir/exercises/luhn/example.exs