Skip to content

Commit

Permalink
Merge pull request #446 from sergeydobrodey/patch-1
Browse files Browse the repository at this point in the history
Refactoring `IsCreditCard`: simplify and optimize code
  • Loading branch information
sergeydobrodey committed Mar 1, 2023
2 parents f21760c + 5a3ee49 commit a9d515a
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -454,27 +454,26 @@ func IsCreditCard(str string) bool {
if !rxCreditCard.MatchString(sanitized) {
return false
}

number, _ := ToInt(sanitized)
number, lastDigit := number / 10, number % 10

var sum int64
var digit string
var tmpNum int64
var shouldDouble bool
for i := len(sanitized) - 1; i >= 0; i-- {
digit = sanitized[i:(i + 1)]
tmpNum, _ = ToInt(digit)
if shouldDouble {
tmpNum *= 2
if tmpNum >= 10 {
sum += (tmpNum % 10) + 1
} else {
sum += tmpNum
for i:=0; number > 0; i++ {
digit := number % 10

if i % 2 == 0 {
digit *= 2
if digit > 9 {
digit -= 9
}
} else {
sum += tmpNum
}
shouldDouble = !shouldDouble

sum += digit
number = number / 10
}

return sum%10 == 0
return (sum + lastDigit) % 10 == 0
}

// IsISBN10 checks if the string is an ISBN version 10.
Expand Down

0 comments on commit a9d515a

Please sign in to comment.