-
Notifications
You must be signed in to change notification settings - Fork 0
/
luhn.go
66 lines (50 loc) · 1.49 KB
/
luhn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (c) 2023-2024 Onur Cinar.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// https://github.com/cinar/checker
package checker
import (
"errors"
"reflect"
)
// tagLuhn is the tag of the checker.
const tagLuhn = "luhn"
// ErrNotLuhn indicates that the given number is not valid based on the Luhn algorithm.
var ErrNotLuhn = errors.New("please enter a valid LUHN")
// doubleTable is the values for the last digits of doubled digits added.
var doubleTable = [10]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}
// IsLuhn checks if the given number is valid based on the Luhn algorithm.
func IsLuhn(number string) error {
digits := number[:len(number)-1]
check := rune(number[len(number)-1])
if calculateLuhnCheckDigit(digits) != check {
return ErrNotLuhn
}
return nil
}
// makeLuhn makes a checker function for the Luhn algorithm.
func makeLuhn(_ string) CheckFunc {
return checkLuhn
}
// checkLuhn checks if the given number is valid based on the Luhn algorithm.
func checkLuhn(value, _ reflect.Value) error {
if value.Kind() != reflect.String {
panic("string expected")
}
return IsLuhn(value.String())
}
// Calculates the Luhn algorighm check digit for the given number.
func calculateLuhnCheckDigit(number string) rune {
digits := []rune(number)
check := 0
for i, j := 0, len(digits)-1; i <= j; i++ {
d := int(digits[j-i] - '0')
if i%2 == 0 {
d = doubleTable[d]
}
check += d
}
check *= 9
check %= 10
return rune('0' + check)
}