Skip to content

Commit

Permalink
refactor into luhn function
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Mueller committed May 20, 2017
1 parent 4ffb388 commit c390949
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
40 changes: 21 additions & 19 deletions lib/ex_junk.ex
Original file line number Diff line number Diff line change
Expand Up @@ -39,26 +39,11 @@ defmodule Junk do
opts = construct_opts(opts)
|> Map.put(:size, 8)
# grab 8 digits, and put a 1 or 2 on the front
base_digits = junk(Integer, opts)
junk(Integer, opts)
|> Integer.digits
|> (fn digits -> [8,0,8,4,0] ++ [Enum.random(1..2)] ++ digits end).()

# starting from the right, doubles digits
# splits into 2 digits where needed
# sums, and adds 24 (for the 80840 of the longer form npi)
check_sum = base_digits
|> Enum.reverse
|> Junk.map_every(2, fn(n) ->Integer.digits(n*2) end)
|> List.flatten
|> Enum.sum

# calcs the check digit
check_digit = case Kernel.rem(check_sum, 10) do
0 -> 0
n -> 10 - n
end

(base_digits ++ [check_digit]) |> Integer.undigits
|> Integer.undigits
|> Junk.luhn
end

def junk(:npi, opts) do
Expand All @@ -79,6 +64,23 @@ defmodule Junk do
end
end

def luhn(number) do
base_digits = Integer.digits(number)
check_sum = base_digits
|> Enum.reverse
|> Junk.map_every(2, fn(n) ->Integer.digits(n*2) end)
|> List.flatten
|> Enum.sum

# calcs the check digit
check_digit = case Kernel.rem(check_sum, 10) do
0 -> 0
n -> 10 - n
end

(base_digits ++ [check_digit]) |> Integer.undigits
end

def map_every(enumerable, nth, mapper) do
{res, _acc} = Enum.map_reduce(enumerable, 0, fn(x, i) -> if (rem(i, nth) == 0) do
{mapper.(x), i+1}
Expand All @@ -94,6 +96,6 @@ defmodule Junk do
end

defp post_op(output, opts) do
output = if opts.prefix, do: "#{opts.prefix}-#{output}", else: output
if opts.prefix, do: "#{opts.prefix}-#{output}", else: output
end
end
4 changes: 4 additions & 0 deletions test/ex_junk_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ defmodule JunkTest do
assert Enum.member?([808401,808402], first_6)
end

test "luhn returns a luhn'd number" do
assert Junk.luhn(80840268496713) == 808402684967138
end

def ssn do
"123-45-6789"
end
Expand Down

0 comments on commit c390949

Please sign in to comment.