Created
January 30, 2019 00:35
-
-
Save dead-claudia/14a365e7aee91009fd8290dad68130d0 to your computer and use it in GitHub Desktop.
Simple ID generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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