Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions Go/shorturl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//ShortURL: Bijective conversion between natural numbers (IDs) and short strings
//Licensed under the MIT License (https://opensource.org/licenses/MIT)
//
//shorturl.Encode() takes an ID and turns it into a short string
//shorturl.Decode() takes a short string and turns it into an ID
//
// Example output:
// 123456789 <=> pgK8p

package shorturl

import "strings"

const (
alphabet = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_"
alphabetLen = len(alphabet)
)

func Encode(n int) string {
sb := strings.Builder{}
for n > 0 {
sb.WriteByte(alphabet[n%alphabetLen])
n = n / alphabetLen
}

return reverse(sb.String())
}

func Decode(s string) (n int) {
for _, r := range s {
n = n*alphabetLen + strings.IndexRune(alphabet, r)
}
return
}

func reverse(s string) string {
runes := []rune(s)
lastIndex := len(s) - 1

for i := 0; i < len(runes)/2; i++ {
runes[i], runes[lastIndex-i] = runes[lastIndex-i], runes[i]
}
return string(runes)
}
31 changes: 31 additions & 0 deletions Go/shorturl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package shorturl

import "testing"

func TestEncode(t *testing.T) {
expected := "pgK8p"
received := Encode(123456789)
if received != expected {
t.Fatalf("Expected: %s, received: %s", expected, received)
}
}

func TestDecode(t *testing.T) {
expected := 123456789
received := Decode("pgK8p")
if received != expected {
t.Fatalf("Expected: %d, received: %d", expected, received)
}
}

func BenchmarkEncode(b *testing.B) {
for n := 0; n < b.N; n++ {
Encode(n)
}
}

func BenchmarkDecode(b *testing.B) {
for n := 0; n < b.N; n++ {
Decode("BCDFGHJP")
}
}