EN
JavaScript - generate unique id (useful in web browser)
2
points
In this short article, we would like to show how to generate a unique id that can be used on UI.
The below solution to provide unique IDs that is created using incremented counter + current time + random number.
The idea bases on:
- incremented counter is always unique per loaded webpage - refresh / reload causes reset,
- current time provides unique time between webpage reloading / refreshing - only incorrect time in the operating system can duplicate values,
- random number increases the probability that generated ID will be unique.
Note: the way how to generate UUID was described in this article.
Advantages: the presented solution has very good performance - better than UUID implementation presented in this article.
Quick solution:
// ONLINE-RUNNER:browser;
var counter = 0;
function renderCounter(base) {
var value = (++counter);
return value.toString(base || 10);
}
function renderTime(base) {
var value = Date.now();
return value.toString(base || 10);
}
function renderRandom(base) {
var value = Math.floor(1e+16 + 9e+16 * Math.random());
return value.toString(base || 10);
}
function generateId(base, separator) {
if (separator == null) {
separator = '-';
}
return renderCounter(base) + separator + renderTime(base) + separator + renderRandom(base);
}
// Usage example:
console.log(generateId(10));
console.log(generateId(16));
console.log(generateId(32));
ES6+ example
// ONLINE-RUNNER:browser;
let counter = 0;
const renderCounter = (base = 10) => {
const value = (++counter);
return value.toString(base);
};
const renderTime = (base = 10) => {
const value = Date.now();
return value.toString(base);
};
const renderRandom = (base = 10) => {
const value = Math.floor(1e+16 + 9e+16 * Math.random());
return value.toString(base);
};
const generateId = (base = 10, separator = '-') => {
return renderCounter(base) + separator + renderTime(base) + separator + renderRandom(base);
};
// Usage example:
console.log(generateId(10));
console.log(generateId(16));
console.log(generateId(32));