-
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(internal): add uniqueid package
- Loading branch information
Showing
2 changed files
with
83 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package uniqueid_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/google/go-cmp/cmp" | ||
"github.com/mrmarble/termsvg/internal/uniqueid" | ||
) | ||
|
||
func TestUniqueID(t *testing.T) { | ||
tests := map[string]struct { | ||
input string | ||
output string | ||
}{ | ||
"Initial": {uniqueid.New().String(), "a"}, | ||
"Next": {runTimes(t, 1).String(), "b"}, | ||
"10 Times": {runTimes(t, 10).String(), "k"}, | ||
"25 Times": {runTimes(t, 25).String(), "z"}, | ||
"26 Times": {runTimes(t, 26).String(), "aa"}, | ||
"27 Times": {runTimes(t, 27).String(), "ab"}, | ||
"51 Times": {runTimes(t, 51).String(), "az"}, | ||
"52 Times": {runTimes(t, 52).String(), "ba"}, | ||
"53 Times": {runTimes(t, 53).String(), "bb"}, | ||
"150 Times": {runTimes(t, 150).String(), "eu"}, | ||
"1500 Times": {runTimes(t, 1500).String(), "zzes"}, | ||
} | ||
for name, test := range tests { | ||
t.Run(name, func(t *testing.T) { | ||
diff(t, test.input, test.output) | ||
}) | ||
} | ||
} | ||
|
||
func runTimes(t *testing.T, times int) *uniqueid.ID { | ||
t.Helper() | ||
|
||
id := uniqueid.New() | ||
for i := 0; i < times; i++ { | ||
id.Next() | ||
} | ||
|
||
return id | ||
} | ||
|
||
func diff(t *testing.T, x interface{}, y interface{}) { | ||
t.Helper() | ||
|
||
diff := cmp.Diff(x, y) | ||
if diff != "" { | ||
t.Fatalf(diff) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
package uniqueid | ||
|
||
type ID []rune | ||
|
||
func New() *ID { | ||
var id ID = []rune{'a'} | ||
|
||
return &id | ||
} | ||
|
||
func (id *ID) String() string { | ||
return string(*id) | ||
} | ||
|
||
func (id *ID) Next() { | ||
for i := len(*id) - 1; i >= 0; i-- { | ||
cur := (*id)[i] | ||
if cur < 'z' { | ||
(*id)[i]++ | ||
return | ||
} | ||
|
||
if i == len(*id)-1 { | ||
(*id)[i] = 'a' | ||
} | ||
|
||
if i == 0 { | ||
*id = append(*id, 'a') | ||
} | ||
} | ||
} |