aboutsummaryrefslogtreecommitdiff
path: root/luhn/luhn.go
blob: 07243204375e857627794eee569cb9fd5560cd6a (plain) (blame)
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
package luhn

import (
	"strconv"

	"github.com/neonxp/checksum"
)

// Check number is correct by luhn algorithm
func Check(number string) error {
	mod := len(number) % 2
	sum := 0
	for i, ch := range number {
		num, err := strconv.Atoi(string(ch))
		if err != nil {
			return checksum.ErrInvalidNumber
		}
		if i%2 == mod {
			if num < 5 {
				sum += num * 2
			} else {
				sum += num*2 - 9
			}
		} else {
			sum += num
		}
	}
	if sum%10 != 0 {
		return checksum.ErrInvalidChecksum
	}
	return nil
}