3

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.

mike2501
  • 141
  • 1
  • 1
  • 11
  • 2
    Have you tried writing your own solution? We can't provide code without your help. – Rafał Figura Apr 26 '21 at 20:42
  • 1
    For the numeric part, generating the ID as an incrementing integer in the backing database is probably the easiest. You might instead look for a solution in that database for how to include letters in such an identifier. – David Apr 26 '21 at 20:46
  • 2
    David's right. UUIDs are unique because it's nearly impossible to generate duplicates. But guaranteeing uniqueness with the scheme `XZ5678` is hard because there are only ~7 million possible values. After generating just 370 IDs, the odds of a duplicate are 1/100. After 1200, 1/10! – backtick Apr 26 '21 at 20:51
  • I haven't tried any solution still. I'm in part of making architecture of my project. This will be small side front-end project since I just learned JS, I made 1 before this. User will be able to create invoices in this application. And invoice cant have same ID as some invoices that already exist. So I don't care if multiple users gets same ID for some invoice. Point is that there shouldn't be 2 invoices for user with same ID's. There will be no database, created invoices will be stored in browser's local storage. This is just show off project I doubt that anyone will create 100 invoices. – mike2501 Apr 26 '21 at 21:08
  • Could you instead base it off the user's ID, an invoice record id, and/or the date? – mykaf Apr 26 '21 at 21:13
  • @mike2501 can you please check my solution? It does what you have asked and also ensures that the new ID is not a duplicate. – Brandon McConnell Apr 26 '21 at 21:17

3 Answers3

5

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);
Brandon McConnell
  • 5,776
  • 1
  • 20
  • 36
1

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);
Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • Yes this is a great solution. It is possible to create duplicates but I think I can create empty array and each time ID is generated check if element like that exists, if it doesn't, then I can push it to array. – mike2501 Apr 26 '21 at 21:15
0

They way of what you are suggesting be pretty sure you are going to get duplicates and collitions, I strongly suggest go with uuid.

Also probably you can find this useful: https://www.npmjs.com/package/short-uuid

Or if you want to continue with your idea this could be helpful: Generate random string/characters in JavaScript