Created
March 3, 2017 08:03
-
-
Save nazieb/5be41eb1ffb863e3b60db9e134f6ec71 to your computer and use it in GitHub Desktop.
ID shortener in Golang
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
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