Created
December 3, 2013 22:05
-
-
Save thataustin/7778287 to your computer and use it in GitHub Desktop.
refactoring a Lund credit card checker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original unrefactored code: | |
class CreditCard | |
#initialize | |
def initialize(card_number) | |
raise ArgumentError.new("Card nunber must be 16 digits long") if card_number.to_s.length != 16 | |
@card_number = cardNumber | |
end | |
#convert a string card number to Luhn Algorithm | |
def luhnConvert(card_number) | |
digits = (card_number).scan(/\d{1}/) #split card number to individual digits | |
for i in 0..(card_number).length | |
if !(i % 2 == 0) #for every number in a odd position | |
digits[i] = (digits[i].to_i * 2).to_s #multiply numbers in odd address by 2 | |
if digits[i].to_i > 9 #if greater than 2 digits | |
digits[i] = sumDigits(digits[i]).to_s #sum the digits | |
end | |
end | |
end | |
return digits #return an array of converted card_number as individual digits | |
end | |
#sum multi-digit number's digits from a string | |
def sumDigits(num) | |
sum = num.scan(/\d{1}/) | |
return sum.inject(0) {|total, digit| total += digit.to_i } | |
end | |
#check card | |
def check_card | |
convertedNumber = luhnConvert(@card_number.to_s) #convert credit card number into Luhn Algorithm form | |
mod10 = convertedNumber.inject(0) { |sum, d| sum += d.to_i } #creates the sum of converted number for %10 test | |
return mod10 % 10 == 0 ? true: false | |
end | |
end | |
# Refactored code | |
class CreditCard | |
def initialize(card_number) | |
raise ArgumentError.new("Card number must be 16 digits long") if card_number.to_s.length != 16 | |
@card_number = card_number | |
end | |
def get_luhn_sum | |
digits = @card_number.to_s.split('').map{|x| x.to_i} | |
for i in 0..@card_number.to_s.length | |
if i % 2 != 0 | |
doubled = digits[i] * 2 | |
digits[i] = (doubled <= 9 ? doubled : doubled - 9) | |
end | |
end | |
digits.reduce(:+) | |
end | |
def check_card | |
get_luhn_sum % 10 == 0 | |
end | |
end | |
# In the end, I changed the way we calculated the sum of 2 digit numbers between 10-20 (which allowed me to remove the sumDigits method), and I used underscore method names instead of camel case |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment