Sha256: 45aa47d2e6a7091279df07ec240a98c78d2bd085374940aac3dcd46a109c5595

Contents?: true

Size: 808 Bytes

Versions: 63

Compression:

Stored size: 808 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

63 entries across 63 versions & 1 rubygems

Version Path
trackler-2.2.1.109 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.108 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.107 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.106 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.105 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.104 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.103 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.102 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.101 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.100 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.99 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.98 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.97 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.96 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.95 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.94 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.93 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.92 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.91 tracks/elixir/exercises/luhn/example.exs
trackler-2.2.1.90 tracks/elixir/exercises/luhn/example.exs