Skip to content

Instantly share code, notes, and snippets.

@tyler-johnson
Last active December 28, 2015 01:59
Show Gist options
  • Save tyler-johnson/7424027 to your computer and use it in GitHub Desktop.
Save tyler-johnson/7424027 to your computer and use it in GitHub Desktop.
Generates a unique string based on the timestamp. Scales across multiple instances if `prepend` argument is set to a unique value. Both produce a similar value, one in base 62 and the other in base 16. Preference comes down to speed and size.
// Slower, larger source, produces a 9 character string
var uniqueId = (function() {
var ALPHA_NUMERIC = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function toAlphaNumeric(n) {
var len = ALPHA_NUMERIC.length,
digits = "";
while (n !== 0) {
var r = n % len;
n = (n - r) / len;
digits = ALPHA_NUMERIC[r] + digits;
}
return digits;
}
var lastTimestamp = null,
counter = 0;
return function(prepend) {
if (prepend == null) prepend = "";
var ts = toAlphaNumeric(Date.now());
if (lastTimestamp !== ts) {
counter = 0;
lastTimestamp = ts;
}
counter++;
var cnt = toAlphaNumeric(counter);
while (cnt.length < 2) { cnt = 0 + cnt; }
return prepend + ts + cnt;
}
})();
// Faster, smaller source, produces a 14 character string
var uniqueId = (function() {
var lastTimestamp = null,
counter = 0;
return function(prepend) {
if (prepend == null) prepend = "";
var ts = Date.now().toString(16);
if (lastTimestamp !== ts) {
counter = 0;
lastTimestamp = ts;
}
counter++;
var cnt = counter.toString(16);
while (cnt.length < 3) { cnt = 0 + cnt; }
return prepend + ts + cnt;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment