Home > Software design >  How to generate unique user ID like Zerodha's user ID with Node.js/JavaScript
How to generate unique user ID like Zerodha's user ID with Node.js/JavaScript

Time:10-01

I'm trying to generate random unique User ID for one of my project and found Zerodha has very easy to remember user ids.

In Zerodha user ID: First two char's are Alphabets and then four char's are numbers.

How to make Id's Like Zerodha: "AC1940","AZ9940", "YM1300" etc.. ?

I wanted them to be unique and easy to remember.

Thank you.

CodePudding user response:

You could generate random alphabets and number from ASCII code and Math.random() function and join them in a string.

const generateCharacter = (base, range) => String.fromCharCode(base   Math.floor(Math.random() * range)),
      userId = Array.from({length: 2}, () => generateCharacter(65, 26)).join('')  
               Array.from({length: 4}, () => generateCharacter(48, 10)).join('');
console.log(userId);

CodePudding user response:

You can create a random 6 digit number as

var randomNumber = (min, max) =>
  Math.floor(Math.random() * (max - min   1))   min;

function generateUUID() {
  const alphabets = [0, 1];
  return Array.from({ length: 6 }, (_, i) => {
    return alphabets.includes(i)
      ? String.fromCharCode(randomNumber(65, 90))
      : randomNumber(0, 9);
  }).join("");
}

console.log( generateUUID() );

CodePudding user response:

By respect of guys methods, those are not standard ways for unique random id. one of the standard and best ways to get random and standard methods for that is UUID.

EDITED:

you can use this uuid nodejs package to install and get the uuid unique random id corrctly.

CodePudding user response:

You might want to use deprecated shortid npm package or popular nanoid. Considering you don't want to get lengthy strings as ID, uuid and similar packages are off the table. Surely using methods to create random strings wouldn't accomplish the purpose as we know that random strings are not necessarily unique.

  • Related