generate 18 digit unique number

Viewed 4060

I want to create a function in my NodeJS application which generates unique 18 digit numbers. What I'm expecting is to get unique 18 digit numbers like below:

73306495056092753667  

I thought of using the below logic, by combining Date.now() with Math.random():

Date.now()+""+Math.floor(Math.random()*10000000)  

But in cases where my function is called exactly at the same millisecond, and if in the same cases, Math.random() returns the same value, the above logic wont return unique ID's.

In NodeJS/Javascript, is there any module like UUID which generates globally unique numerical values? Or can anyone help me create an algorithm that will generate unique ID's?

3 Answers

Here is a solution using nanoid (npm install -S nanoid):

const { customAlphabet } = require('nanoid')
const nanoid = customAlphabet('1234567890', 18)
console.log(nanoid()) // sample outputs => 455712511712968405, 753952709650782495

Try appending a random number between 10000 and 99999 to new Date().valueOf()

const numbers = [...Array(90000).keys()].map(n => n + 10000);
let filteredNumbers = numbers;
let timeStamp = new Date().valueOf();
let rand = 0;
const generateRandomNumber = _ => {
  const currentTimeStamp = new Date().valueOf();
  if (timeStamp === currentTimeStamp && rand !== 0) {
    filteredNumbers = filteredNumbers.filter(n => n !== value)
  } else {
    timeStamp = currentTimeStamp;
    filteredNumbers = numbers;
  }
  rand = filteredNumbers[Math.floor(Math.random() * filteredNumbers.length)];
  return parseInt(new Date().valueOf() + "" + rand, 10);
};

document.querySelector('#generate')
  .addEventListener('click', _ => {
    const uuid = generateRandomNumber();
    console.log(uuid);
  });
<button id="generate">Generate UUID</button>

Exactly Same 18 Digits as my laravel Projects

Well In this case I Created that with 10 digiths Seconds + randomiser like 3+3+2 digits Maybe It Kind of what @Naveen did

Related