Skip to content

Instantly share code, notes, and snippets.

@derMani
Forked from fiznool/hashid.js
Last active January 24, 2021 18:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derMani/9db056cfd526b553abdc to your computer and use it in GitHub Desktop.
Save derMani/9db056cfd526b553abdc to your computer and use it in GitHub Desktop.
Short 'hash' ID generator.
'use strict';
/**
* The default alphabet is 25 numbers and lowercase letters.
* Any numbers that look like letters and vice versa are removed:
* 1 l, 0 o.
* Also the following letters are not present, to prevent any
* expletives: cfhistu
*/
var DEFAULT_ALPHABET =
'23456789abdegjkmnpqrvwxyz';
// Governs the length of the ID.
// With an alphabet of 25 chars,
// a length of 8 gives us 25^8 or
// 152,587,890,625 possibilities.
// Should be enough...
var DEFAULT_ID_LENGTH = 5;
/**
* Governs the number of times we should try to find
* a unique value before giving up.
* @type {Number}
*/
var UNIQUE_RETRIES = 9999;
var HashID = {};
/**
* Returns a randomly-generated friendly ID.
* Note that the friendly ID is not guaranteed to be
* unique to any other ID generated by this same method,
* so it is up to you to check for uniqueness.
* @return {String} friendly ID.
*/
HashID.generate = function(alphabetOptions) {
var options = alphabetOptions || {};
var alphabet = options.alphabet || DEFAULT_ALPHABET;
var idLength = options.idLength || DEFAULT_ID_LENGTH;
var rtn = '';
for (var i = 0; i < idLength; i++) {
rtn += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
}
return rtn;
};
/**
* Tries to generate a unique ID that is not defined in the
* `previous` array.
* @param {Array} previous The list of previous ids to avoid.
* @return {String} A unique ID, or `null` if one could not be generated.
*/
HashID.generateUnique = function(previous) {
previous = previous || [];
var retries = 0;
var id;
// Try to generate a unique ID,
// i.e. one that isn't in the previous.
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