unique-id-generator-javascript
Version:
Generates an Unique ID of 9 characters as string you can also increase the length of your ID
25 lines (24 loc) • 1.15 kB
JavaScript
const possibleChars = ['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', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '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'];
exports.getUniqueId = (idLength = 9) => {
if (typeof idLength == "number") {
if (idLength > 9) {
idLength = idLength
} else {
idLength = 9;
}
const itration = idLength - 5;
let uniqueId = '';
const dateNow = Date.now() + '';
const uniqueToApend = dateNow.substring(dateNow.length - 5);
for (let i = 0; i < itration; i++) {
uniqueId += possibleChars[Math.floor(Math.random() * possibleChars.length)];
}
uniqueId = uniqueToApend.substring(0, 2) + uniqueId + uniqueToApend.substring(2);
return uniqueId;
} else {
return new TypeError("Please pass a valid length of type number to get uniqueId if you want id length to be greater than 9");
}
}