Skip to content

Commit

Permalink
feat(internal): add uniqueid package
Browse files Browse the repository at this point in the history
  • Loading branch information
MrMarble committed Mar 8, 2022
1 parent 86a017a commit fcc29ad
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
52 changes: 52 additions & 0 deletions internal/uniqueid/unique_test.go
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)
}
}
31 changes: 31 additions & 0 deletions internal/uniqueid/uniqueid.go
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')
}
}
}

0 comments on commit fcc29ad

Please sign in to comment.