Skip to content

Instantly share code, notes, and snippets.

@niklas-r
Last active August 29, 2015 13:57
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 niklas-r/9408235 to your computer and use it in GitHub Desktop.
Save niklas-r/9408235 to your computer and use it in GitHub Desktop.
Generate a UID with an optional paramenter to set length. Thanks to http://stackoverflow.com/a/8809472
/**
* Generate a unique ID
*
* @param {Number} [len=15] - Optionally set a length of the generated string.
* Defaults to 15 characters, it's not recommended
* to go much lower than this in order to ensure
* uniqueness.
*
* @return {string} A unique ID.
*/
function uniqueId (len) {
var d = new Date().getTime(),
Xs;
len = len || 15;
Xs = new Array(len + 1).join('x');
return '_' + Xs.replace(/x/g, function (c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c==='x' ? r : (r&0x7|0x8)).toString(16);
});
};
describe("uniqueId", function() {
it("should generate a UID", function() {
var UIDs = [],
last,
duplicate,
i;
// Generate UID's and store them
for (i = 0; i < 1e4; i++) {
UIDs.push(uniqueId());
}
// Sorting UIDs so we can compare
UIDs.sort();
// Set initial array item to compare with
last = UIDs[0];
for (i = 1; i < UIDs.length; i++) {
// Always compare current array item to the previous one
if (UIDs[i] === last) {
// If we've done a good job this should never happen
duplicate = true;
break;
}
last = UIDs[i];
}
expect(duplicate).toBeFalsy();
});
it("should generate a UID with a minimum length", function() {
expect(uniqueId()).toMatch(/_\w{15}/);
});
it("should generate a UID with a set length", function() {
var regex;
for (var i = 1; i <= 20; i++) {
regex = new RegExp('_\\w{' + i + '}');
expect(uniqueId(i)).toMatch(regex);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment