-
-
Save garenyondem/17cda09a17c1d830cb6c35ad50adb82a to your computer and use it in GitHub Desktop.
Short 'hash' 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'; | |
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+'; | |
const ALPHABET_LENGTH = ALPHABET.length; | |
const ID_LENGTH = 8; | |
const UNIQUE_RETRIES = 9999; | |
let HashID = {}; | |
HashID.generate = function () { | |
let rtn = ''; | |
for (let i = 0; i < ID_LENGTH; i++) { | |
rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET_LENGTH)); | |
} | |
return rtn; | |
}; | |
HashID.generateUnique = function (previous) { | |
previous = previous || []; | |
let retries = 0; | |
let id; | |
while (!id && retries < UNIQUE_RETRIES) { | |
id = HashID.generate(); | |
if (previous.indexOf(id) !== -1) { | |
id = null; | |
retries++; | |
} | |
} | |
return id; | |
}; | |
module.exports = HashID; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment