Skip to content

Instantly share code, notes, and snippets.

@edulan
Created May 18, 2020 23:54
Show Gist options
  • Save edulan/ee2d5cbc1f9630146e46f5fcd1b60ba8 to your computer and use it in GitHub Desktop.
Save edulan/ee2d5cbc1f9630146e46f5fcd1b60ba8 to your computer and use it in GitHub Desktop.
Custom base32 generator
const ALPHABET = "RKYM5C4H07P9EGWJ1BZQ8V3S62FXNTDA"
const BASE_LENGTH = ALPHABET.length
const SHORT_CODE_LENGTH = 6
function toBase (input) {
let number = input
if (number === 0) {
return ALPHABET[0]
}
let result = ''
while (number > 0) {
const rest = number % BASE_LENGTH
result = `${ALPHABET[rest]}${result}`
number = Math.floor(number / BASE_LENGTH)
}
return result
}
function generateShortCode (input) {
const lower = Math.pow(BASE_LENGTH, SHORT_CODE_LENGTH - 1)
const upper = Math.pow(BASE_LENGTH, SHORT_CODE_LENGTH) - 1
const range = upper - lower
const size = 1E2
const offset = Math.floor(range / Math.min(size, range))
const number = lower + (offset * input)
return toBase(number)
}
console.log(generateShortCode(1))
console.log(generateShortCode(2))
console.log(generateShortCode(3))
console.log(generateShortCode(4))
console.log(generateShortCode(5))
console.log(generateShortCode(6))
console.log(generateShortCode(7))
console.log(generateShortCode(8))
console.log(generateShortCode(9))
console.log(generateShortCode(10))
// K7TWYB
// KQFNCY
// KT6PHQ
// YHV6P5
// YBQ4EV
// YX18J4
// MCWYBS
// MJ9180
// M20D32
// 5M4E2P
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment