diff options
author | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2019-08-30 02:53:06 +0300 |
---|---|---|
committer | Alexander Kiryukhin <a.kiryukhin@mail.ru> | 2019-08-30 02:53:06 +0300 |
commit | dd42100aa2f062a4e53399a3cabce732eaf0f6e5 (patch) | |
tree | 5913585fe0878b3cb4b4fe852f3b3345cfca4f94 /barcode | |
parent | 878cb24695b7d39fa9de65a1e164abc84dc67ead (diff) |
Diffstat (limited to 'barcode')
-rw-r--r-- | barcode/barcode.go | 35 | ||||
-rw-r--r-- | barcode/barcode_test.go | 22 |
2 files changed, 57 insertions, 0 deletions
diff --git a/barcode/barcode.go b/barcode/barcode.go new file mode 100644 index 0000000..f400002 --- /dev/null +++ b/barcode/barcode.go @@ -0,0 +1,35 @@ +package barcode + +import ( + "strconv" + "strings" + + "github.com/neonxp/checksum" +) + +// Check barcode +func Check(number string) error { + sum := 0 + numbers := strings.Split(number, "") + l := len(numbers) + for i := l; i > 0; i-- { + ch := numbers[i-1] + num, err := strconv.Atoi(string(ch)) + if err != nil { + return checksum.ErrInvalidNumber + } + if (l-i)%2 != 0 { + sum += num * 3 + } else { + sum += num + } + } + if sum%10 != 0 { + return checksum.ErrInvalidChecksum + } + return nil +} + +func Generate(number string) (string, error) { + return "", checksum.ErrNotImplemented +} diff --git a/barcode/barcode_test.go b/barcode/barcode_test.go new file mode 100644 index 0000000..573691b --- /dev/null +++ b/barcode/barcode_test.go @@ -0,0 +1,22 @@ +package barcode + +import ( + "testing" + + "github.com/neonxp/checksum" +) + +func TestBarcode(t *testing.T) { + samples := map[string]error{ + "4600051000058": checksum.ErrInvalidChecksum, + "A600051000057": checksum.ErrInvalidNumber, + "4600051000057": nil, + "46009333": nil, + "041689300494": nil, + } + for num, result := range samples { + if err := Check(num); err != result { + t.Errorf("Expected %+v actual %+v for %s", result, err, num) + } + } +} |