// Package luhn is for validating per the Luhn formula.
package luhn
import (
"log"
"strconv"
"strings"
"unicode"
)
// Valid returns true if input is valid according to Luhn formula, false otherwise.
func Valid(input string) bool {
input = strings.ReplaceAll(input, " ", "")
if len(input) <= 1 {
return false
}
for _, ch := range input {
if !unicode.IsDigit(ch) {
return false
}
}
return luhn(input)%10 == 0
}
func luhn(input string) int {
var sum int
var second bool
for i := len(input) - 1; i >= 0; i-- {
digit, err := strconv.Atoi(string(input[i]))
if err != nil {
log.Panicf("error converting %q to int: %s", input[i], err)
}
if !second {
sum += digit
second = true
continue
}
digit *= 2
if digit > 9 {
digit -= 9
}
sum += digit
second = false
}
return sum % 10
}