From 7823443488844d47c8f187d4af9476fda7560de7 Mon Sep 17 00:00:00 2001 From: Arnas Udovic Date: Thu, 8 Aug 2024 18:25:21 +0300 Subject: [PATCH] added negative support --- CHANGELOG | 3 +++ abcex.go | 19 +++++++++++++++++++ abcex_test.go | 31 ++++++++++++++++++++++--------- 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 8514ef1..fc65189 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,2 +1,5 @@ +v1.0.2, released 2024-08-08 + * support negative values + v1.0.1, released 2024-08-08 * fix encoding to zero diff --git a/abcex.go b/abcex.go index 8cb012d..5b0003a 100644 --- a/abcex.go +++ b/abcex.go @@ -38,23 +38,42 @@ func Encode(number int64) string { } result := "" + negative := false + if number < 0 { + number = number * (-1) + negative = true + } for number > 0 { result = fmt.Sprintf("%s%s", decToAbcex[int(number%36)], result) number /= 36 } + if negative { + return "-" + result + } + return result } func Decode(str string) int64 { var result int64 result = 0 + negative := false + if string(str[0]) == "-" { + negative = true + str = str[1:] + } + str = reverse(str) for i, c := range str { result = int64(math.Pow(36, float64(i)))*int64(abcexToDec[string(c)]) + result } + if negative { + return result * (-1) + } + return result } diff --git a/abcex_test.go b/abcex_test.go index 9c7f646..c7365ed 100644 --- a/abcex_test.go +++ b/abcex_test.go @@ -1,24 +1,37 @@ package abcex import ( - "fmt" "testing" ) func TestEncode(t *testing.T) { - fmt.Println(Encode(12345)) - // Output: 9ix + if Encode(12345) != "9ix" { + t.Fatal("Failed encoding") + } } func TestDecode(t *testing.T) { - fmt.Println(Decode("9ix")) - // Output: 12345 + if Decode("9ix") != 12345 { + t.Fatal("Failed decoding") + } } func TestZero(t *testing.T) { - fmt.Println(Encode(0)) - // Output: 0 + if Encode(0) != "0" { + t.Fatal("Failed zero encoding") + } - fmt.Println(Decode("0")) - // Output: 0 + if Decode("0") != 0 { + t.Fatal("Failed zero decoding") + } +} + +func TestNegative(t *testing.T) { + if Encode(-20) != "-k" { + t.Fatal("Failed negative encoding:", Encode(-20)) + } + + if Decode("-ab") != -371 { + t.Fatal("Failed negative decoding", Decode("-ab")) + } }