Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Company.luhn_algorithm and add missing tests. #1335

Merged
merged 2 commits into from
Sep 4, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/faker/company.rb
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def mod11(number)
def luhn_algorithm(number)
multiplications = []

number.split(//).each_with_index do |digit, i|
number.reverse.split(//).each_with_index do |digit, i|
multiplications << if i.even?
digit.to_i * 2
else
Expand Down
24 changes: 24 additions & 0 deletions test/test_faker_company.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ def test_south_african_trust_registration_number
)
end

def test_luhn_algorithm
01max marked this conversation as resolved.
Show resolved Hide resolved
# Odd length base for luhn algorithm
odd_base = Faker::Number.number([5, 7, 9, 11, 13].sample)
odd_luhn_complement = @tester.send(:luhn_algorithm, odd_base)
odd_control = "#{odd_base}#{odd_luhn_complement}"

# Even length base for luhn algorithm
even_base = Faker::Number.number([4, 6, 8, 10, 12].sample)
even_luhn_complement = @tester.send(:luhn_algorithm, even_base)
even_control = "#{even_base}#{even_luhn_complement}"

assert((luhn_checksum(odd_control) % 10).zero?)
assert((luhn_checksum(even_control) % 10).zero?)
end

private

def czech_o_n_checksum(org_no)
Expand All @@ -163,4 +178,13 @@ def abn_checksum(abn)
(i.zero? ? n - 1 : n) * abn_weights[i]
end.inject(:+)
end

def luhn_checksum(luhn)
luhn_split = luhn.each_char.map(&:to_i).reverse.each_with_index.map do |n, i|
x = i.odd? ? n * 2 : n
x > 9 ? x - 9 : x
end

luhn_split.compact.inject(0) { |sum, x| sum + x }
end
end