Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to generate unique ID

I want to generate unique ID in JavaScript. I have tried uuid npm package, it's good but it's not what I want.

For example what I get as a result from generating unique ID from uuid package is

9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

Is there any way to make specific format as I want.

For example I want my ID to look like this

XZ5678

In this example format is two uppercase letters and 4 numbers.

That's it, I'm looking for answer and thank you all in advance.

like image 374
mike2501 Avatar asked Sep 05 '25 03:09

mike2501


2 Answers

If you're just looking to generate a random sequence according to that pattern, you can do so relatively easily. To ensure it's unique, you'll want to run this function and then match it against a table of previously generated IDs to ensure it has not already been used.

In my example below, I created two functions, getRandomLetters() and getRandomDigits() which return a string of numbers and letters the length of the argument passed to the function (default is length of 1 for each).

Then, I created a function called generateUniqueID() which generates a new ID according to the format you specified. It checks to see if the ID already exists within a table of exiting IDs. If so, it enters a while loop which loops until a new unique ID is created and then returns its value.

const existingIDs = ['AA1111','XY1234'];
const getRandomLetters = (length = 1) => Array(length).fill().map(e => String.fromCharCode(Math.floor(Math.random() * 26) + 65)).join('');
const getRandomDigits = (length = 1) => Array(length).fill().map(e => Math.floor(Math.random() * 10)).join('');
const generateUniqueID = () => {
  let id = getRandomLetters(2) + getRandomDigits(4);
  while (existingIDs.includes(id)) id = getRandomLetters(2) + getRandomDigits(4);
  return id;
};
const newID = generateUniqueID();

console.log(newID);
like image 199
Brandon McConnell Avatar answered Sep 08 '25 16:09

Brandon McConnell


Not sure why you want this pattern but you could do like this:

const { floor, random } = Math;

function generateUpperCaseLetter() {
  return randomCharacterFromArray('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
}

function generateNumber() {
  return randomCharacterFromArray('1234567890');
}

function randomCharacterFromArray(array) {
  return array[floor(random() * array.length)];
}

const identifiers = [];

function generateIdentifier() {
  const identifier = [
    ...Array.from({ length: 2 }, generateUpperCaseLetter),
    ...Array.from({ length: 4 }, generateNumber)
  ].join('');

  // This will get slower as the identifiers array grows, and will eventually lead to an infinite loop
  return identifiers.includes(identifier) ? generateIdentifier() : identifiers.push(identifier), identifier;
}

const identifier = generateIdentifier();

console.log(identifier);
like image 33
Guerric P Avatar answered Sep 08 '25 17:09

Guerric P