@scania/tegel
Version:
Tegel Design System
26 lines (25 loc) • 1.39 kB
JavaScript
/**
* Generates a reasonably unique string ID based on current time (minutes, seconds, milliseconds) and random numbers.
*
* This function combines the current time and random numbers to generate
* a unique string ID. The function assumes that it won't be called frequently
* enough to generate two identical IDs within a millisecond, or that the random
* number generator will produce the same value twice in quick succession.
*
* Note: The IDs generated by this function are not globally unique and their length may vary.
* For truly unique and fixed-length IDs, consider using a more robust method such as UUID.
*
* @returns {string} A unique string ID.
*/
function generateUniqueId() {
const now = new Date();
const timeInMilliseconds = now.getMinutes() * 60000 + now.getSeconds() * 1000 + now.getMilliseconds(); // Get current time in milliseconds from the start of the hour
const randomNum1 = Math.floor(Math.random() * 1000000); // Random number between 0 and 999999
const randomNum2 = Math.floor(Math.random() * 1000000); // Another random number
// Convert to base 36 (using numbers and letters) and remove '0.' from the random number
const uniqueString = randomNum1.toString(36).substring(2) +
timeInMilliseconds.toString(36) +
randomNum2.toString(36).substring(2);
return uniqueString;
}
export default generateUniqueId;