Skip to content

Instantly share code, notes, and snippets.

@mtarnovan
Created May 14, 2016 17:25
Show Gist options
  • Save mtarnovan/53448e5ce4158a98ff9770173b40374e to your computer and use it in GitHub Desktop.
Save mtarnovan/53448e5ce4158a98ff9770173b40374e to your computer and use it in GitHub Desktop.
defmodule CifValidator do
@test_key "753217532"
def valid_cif?(cif) do
well_formed?(cif) && control_sum_matches?(cif)
end
defp control_sum_matches?(cif) do
test_key = @test_key
|> to_integer_list
|> Enum.reverse
[control | rest] = cif
|> to_integer_list
|> Enum.reverse
rest
|> Enum.zip(test_key)
|> Enum.map(fn {a, b} -> a * b end)
|> Enum.sum
|> Kernel.*(10)
|> rem(11)
|> rem(10)
|> Kernel.===(control)
end
defp well_formed?(cif) do
Regex.match?(~r/^\d{2,10}$/, cif)
end
defp to_integer_list(string) do
string
|> String.to_char_list
|> Enum.map(fn(x) -> String.to_integer << x >> end)
end
end
defmodule OpenapiRest.CifValidatorTest do
use ExUnit.Case
@valid_cifs [
"20959993",
"18834610",
"14752305",
"21237710",
"17732264"
]
@invalid_cifs [
"z",
"12345678",
"RO20959993",
""
]
test "valid cifs" do
assert Enum.all?(@valid_cifs, fn(x) -> OpenapiRest.CifValidator.valid_cif?(x); end)
end
test "invalid cifs" do
assert Enum.all?(@invalid_cifs, fn(x) -> !OpenapiRest.CifValidator.valid_cif?(x); end)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment