Skip to content

Instantly share code, notes, and snippets.

@follesoe
Forked from esamattis/urlshortener.coffee
Created February 28, 2013 15:24
Show Gist options
  • Select an option

  • Save follesoe/5057517 to your computer and use it in GitHub Desktop.

Select an option

Save follesoe/5057517 to your computer and use it in GitHub Desktop.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".split("")
base = alphabet.length
exports.encode = (i) ->
return alphabet[0] if i is 0
s = ""
while i > 0
s += alphabet[i % base]
i = parseInt(i / base, 10)
s.split("").reverse().join("")
exports.decode = (s) ->
i = 0
for c in s
i = i * base + alphabet.indexOf c
i
# Poor man's test case
if require.main is module
for i in [0..100000]
if exports.decode(exports.encode(i)) isnt i
console.log exports.encode(i), i, "is not", exports.decode(exports.encode(i))
console.log "error"
break
console.log "done"
@follesoe
Copy link
Copy Markdown
Author

Usefull for creating short alpha keys for numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment