Skip to content

Instantly share code, notes, and snippets.

@garenyondem
Forked from fiznool/hashid.js
Last active September 30, 2018 19:30
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 garenyondem/17cda09a17c1d830cb6c35ad50adb82a to your computer and use it in GitHub Desktop.
Save garenyondem/17cda09a17c1d830cb6c35ad50adb82a to your computer and use it in GitHub Desktop.
Short 'hash' ID generator.
'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