Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate 18 digit unique number

Tags:

javascript

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?

like image 792
Tony Mathew Avatar asked Sep 06 '25 03:09

Tony Mathew


1 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
like image 85
Tibebes. M Avatar answered Sep 07 '25 23:09

Tibebes. M