Skip to content

Instantly share code, notes, and snippets.

@nazieb
Created March 3, 2017 08:03
Show Gist options
  • Save nazieb/5be41eb1ffb863e3b60db9e134f6ec71 to your computer and use it in GitHub Desktop.
Save nazieb/5be41eb1ffb863e3b60db9e134f6ec71 to your computer and use it in GitHub Desktop.
ID shortener in Golang
package shortener
import (
"strings"
)
var shortenerDict = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789` // you can customize this, just make sure there's no duplicate chars
var shortenerBase = len(shortenerDict)
func ShortenID(ID int64) string {
result := ""
for ID > 0 {
mod := ID % int64(shortenerBase)
result = shortenerDict[int(mod):int(mod)+1] + result
ID /= int64(shortenerBase)
}
return result
}
func ExpandShortID(shortID string) int64 {
var id int
for i, char := range shortID {
index := strings.Index(shortenerDict, string(char))
id += index
if i < len(shortID)-1 {
id *= shortenerBase
}
}
return int64(id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment