Skip to content

Instantly share code, notes, and snippets.

@fiznool
Created November 16, 2014 09:45
Show Gist options
  • Save fiznool/73ee9c7a11d1ff80b81c to your computer and use it in GitHub Desktop.
Save fiznool/73ee9c7a11d1ff80b81c 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 ALPHABET =
'23456789abdegjkmnpqrvwxyz';
var ALPHABET_LENGTH = ALPHABET.length;
// 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 ID_LENGTH = 8;
/**
* 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() {
var rtn = '';
for (var i = 0; i < ID_LENGTH; 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;
@srinivas1918
Copy link

is this will generate unique even after node js server restarts?

@derMani
Copy link

derMani commented Sep 16, 2015

No, for this purpose you have to store the IDs in some kind of database.
You can pass an array of previous IDs to this module.

Btw @fiznool: I've updated your gist for my needs. I needed a configurable length and alphabet at runtime, so I just passed a few options to your module. Defaults will be used if no options are provided.

https://gist.github.com/derMani/9db056cfd526b553abdc

Regards
derMani

@cbess
Copy link

cbess commented Jul 14, 2016

@natan88
Copy link

natan88 commented Apr 25, 2018

In your opinion, for a simpler case, would Math.random().ToString(36).substr(2, length) suffice?
Thank you!

@zomars
Copy link

zomars commented Jun 16, 2021

Can you "dehash" a hashed string back to normal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment