added negative support
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Arnas Udovic 2024-08-08 18:25:21 +03:00
parent 90bf8beb0c
commit 7823443488
3 changed files with 44 additions and 9 deletions

View file

@ -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

View file

@ -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
}

View file

@ -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"))
}
}