Skip to content

Instantly share code, notes, and snippets.

@dead-claudia
Created January 30, 2019 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dead-claudia/14a365e7aee91009fd8290dad68130d0 to your computer and use it in GitHub Desktop.
Save dead-claudia/14a365e7aee91009fd8290dad68130d0 to your computer and use it in GitHub Desktop.
Simple ID generator
"use strict"
// Creates a `generate` function using an alphabet, for optimally small IDs
// if you can only use certain characters. This could be useful for file name
// generators, minifiers, among many others. You *do* need to expand letter
// ranges, though.
module.exports = alphabet => {
const charTable = [...new Set(Array.from(alphabet, x => `${x}`))]
let counter = 0
if (charTable.length < 2) {
throw new TypeError("alphabet must have at least two distinct values")
}
return () => {
let id = counter++
const name = []
while (id >= charTable.length) {
name.push(charTable[id % charTable.length])
id = id / charTable.length | 0
}
return name.reverse().join("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment