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