aboutsummaryrefslogtreecommitdiff
path: root/luhn
diff options
context:
space:
mode:
authorAlexander Kiryukhin <a.kiryukhin@mail.ru>2019-08-30 01:26:24 +0300
committerAlexander Kiryukhin <a.kiryukhin@mail.ru>2019-08-30 01:26:24 +0300
commit2d69c4db4db25e256c22b8fd544dc7b95d71da9c (patch)
tree4a0f35c6b88b92305d460f4ebbd4d81619f1def0 /luhn
Initial
Diffstat (limited to 'luhn')
-rw-r--r--luhn/luhn.go32
-rw-r--r--luhn/luhn_test.go20
2 files changed, 52 insertions, 0 deletions
diff --git a/luhn/luhn.go b/luhn/luhn.go
new file mode 100644
index 0000000..0724320
--- /dev/null
+++ b/luhn/luhn.go
@@ -0,0 +1,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
+}
diff --git a/luhn/luhn_test.go b/luhn/luhn_test.go
new file mode 100644
index 0000000..ea36119
--- /dev/null
+++ b/luhn/luhn_test.go
@@ -0,0 +1,20 @@
+package luhn
+
+import (
+ "testing"
+
+ "github.com/neonxp/checksum"
+)
+
+func TestLuhn(t *testing.T) {
+ samples := map[string]error{
+ "4561261212345464": checksum.ErrInvalidChecksum,
+ "A561261212345464": checksum.ErrInvalidNumber,
+ "4561261212345467": nil,
+ }
+ for num, result := range samples {
+ if err := Check(num); err != result {
+ t.Errorf("Expected %+v actual %+v", result, err)
+ }
+ }
+}