Skip to content

Instantly share code, notes, and snippets.

@tiagodll
Created March 10, 2020 16:22
Show Gist options
  • Save tiagodll/b4fb7d7fd6bc65d5a0703d18c66db15e to your computer and use it in GitHub Desktop.
Save tiagodll/b4fb7d7fd6bc65d5a0703d18c66db15e to your computer and use it in GitHub Desktop.
64id - an id encoding for more readable urls, but still keeping a long number
function EncodeDigit(digit) {
if (digit < 10)
return digit + 48
else if (digit < 36)
return digit + 97 - 10
else if (digit < 62)
return digit + 65 - 36
else if (digit == 62)
return "_"
else if (digit == 63)
return "$"
}
function EncodeNumber(number) {
let digit = EncodeDigit(number % 64);
// console.log(`char[${number % 64}] = ${digit} => ${String.fromCodePoint(digit)}`)
let x = (number >= 64 ? EncodeNumber(Math.floor(number / 64)) : "") + String.fromCodePoint(digit);
return x;
}
function DecodeDigit(char) {
let digit = char.charCodeAt(0);
if (digit == 95)
return 62
if (digit == 36)
return 63
if (digit >= 97)
return digit - 87
if (digit >= 65)
return digit - 29
if (digit >= 48)
return digit - 48
}
function DecodeNumber(number) {
return [...number].reduceRight((acc, x, i) => {
let digit = DecodeDigit(x)
let index = Math.pow(64, number.length - i - 1)
let value = index * digit
// console.log(`[${x}] = ${digit} * 64^${index} = ${value} | acc: ${acc}`)
return acc + value
}, 0)
}
let encoded = EncodeNumber(123454321)
console.log(encoded);
console.log(DecodeNumber(encoded));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment