Add identifier function for use in templates.

This commit is contained in:
Aaron L 2016-07-01 15:52:40 -07:00
parent 9a80de4103
commit ce30724f98
2 changed files with 53 additions and 0 deletions

View file

@ -6,11 +6,42 @@ package strmangle
import (
"fmt"
"math"
"strings"
"github.com/jinzhu/inflection"
)
var (
idAlphabet = []byte("abcdefghijklmnopqrstuvwxyz")
)
// Identifier creates an identifier useful for a query
// This is essentially a base conversion from Base 10 integers to Base 26
// integers that are represented by an alphabet from a-z
// See tests for example outputs.
func Identifier(in int) string {
ln := len(idAlphabet)
var n int
if in == 0 {
n = 1
} else {
n = 1 + int(math.Log(float64(in))/math.Log(float64(ln)))
}
cols := make([]byte, n)
for i := 0; i < n; i++ {
divisor := int(math.Pow(float64(ln), float64(n-i-1)))
rem := in / divisor
cols[i] = idAlphabet[rem]
in -= rem * divisor
}
return string(cols)
}
// Plural converts singular words to plural words (eg: person to people)
func Plural(name string) string {
splits := strings.Split(name, "_")

View file

@ -5,6 +5,28 @@ import (
"testing"
)
func TestIDGen(t *testing.T) {
t.Parallel()
tests := []struct {
In int
Out string
}{
{In: 0, Out: "a"},
{In: 25, Out: "z"},
{In: 26, Out: "ba"},
{In: 52, Out: "ca"},
{In: 675, Out: "zz"},
{In: 676, Out: "baa"},
}
for _, test := range tests {
if got := Identifier(test.In); got != test.Out {
t.Errorf("[%d] want: %q, got: %q", test.In, test.Out, got)
}
}
}
func TestDriverUsesLastInsertID(t *testing.T) {
t.Parallel()