How to generate unique ID with node.js

前端 未结 14 1878
感动是毒
感动是毒 2020-12-12 10:17
function generate(count) {
    var founded = false,
        _sym = \'abcdefghijklmnopqrstuvwxyz1234567890\',
        str = \'\';
    while(!founded) {
        for(va         


        
14条回答
  •  我在风中等你
    2020-12-12 11:06

    Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

    Math.random()
    

    The chances of fractions being the same in a real space [0, 1] is theoratically 0 and approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

    I call this the "Chong-Fractional-Unique-ID".

    Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

    random_numbers = [] 
    for (i = 0; i < 1000000; i++) { 
       random_numbers.push(Math.random()) 
       //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
    } 
    
    if (i === 1000000) { 
       console.log("Before checking duplicate") 
       console.log(random_numbers.length) 
       console.log("After checking duplicate") 
       random_set = new Set(random_numbers) 
       console.log([...random_set].length) // length is still the same
    } 
    

提交回复
热议问题