JS generates unique ID methods: UUID and NanoID

JS generates unique ID methods: UUID and NanoID

Preface:

There is a better way to have a unique ID, which is NanoID . Today's article records that NanoID is replacing UUID? And js method to generate uuid and NanoID.

1. Why NanoID is replacing UUID

1. Safer In most random generators, they use the unsafe Math.random() . However, NanoID uses crypto module and the Web Crypto API , which means NanoID is more secure. Additionally, NanoID uses its own algorithm, called the unified algorithm, in its ID generator implementation, instead of using random % alphabet .

2. It is fast and compact. NanoID is 60% faster than UUID . Unlike the 36-character alphabet of UUIDs, NanoIDs have only 21 characters.

In addition, NanoID supports 14 different programming languages, which are:

C#, C++, Clojure and ClojureScript, Crystal, Dart & Flutter, Deno, Go, Elixir, Haskell, Janet, Java, Nim, Perl, PHP, Python with dictionaries, Ruby, Rust, Swift


3. Compatibility

It also supports PouchDB , CouchDB WebWorkers , Rollup , and libraries such as React and Reach-Native . We can get the unique ID in the terminal using npx nanoid .

2. How to generate js

Let's see how they are generated using js

First of all, let’s talk about how we generated uuid before

Method 1:

function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}
guid() // "a1ca0f7b-51bd-4bf3-a5d5-6a74f6adc1c7"


Method 2:

var _S4 = function() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}

// Get the unique ID of the ad request. Is it the current timestamp + 13 random digits? export function GetsingleId() {
  var _res = (_S4() + _S4() + '-' + _S4() + '-' + _S4() + '-' + _S4() + '-' + _S4() + _S4() + _S4())
  return '_' + config.version + '_' + _res
}


Method 3:

function uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
}
uuid() // "ffb7cefd-02cb-4853-8238-c0292cf988d5"


3. NanoID method

import { nanoid } from 'nanoid'
let idA = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
//You can also specify the length of the generated string let idB = nanoid(5)


It can be installed mainly in the form of npm package. The core code is as follows:

let urlAlphabet =
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'

let nanoid = (size = 21) => {
  let id = ''
  // A compact alternative for `for (var i = 0; i < step; i++)`.
  let i = size
  while (i--) {
    // `| 0` is more compact and faster than `Math.floor()`.
    id += urlAlphabet[(Math.random() * 64) | 0]
  }
  return id
}

This is the end of this article about UUID and NanoID, which are the methods for generating unique IDs in JS. For more information about how to generate unique IDs in JS, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to generate UUID with two lines of Javascript code
  • JS implements a complete example of how to generate UUID by clicking [based on jQuery]
  • Example of how to generate UUID using JS
  • Javascript method to generate globally unique identifier (GUID, UUID)

<<:  The difference between div and table in speed, loading, web application, etc.

>>:  Detailed explanation of MySql data type tutorial examples

Recommend

Analyze MySQL replication and tuning principles and methods

1. Introduction MySQL comes with a replication so...

Detailed explanation of Linux lsof command usage

lsof (list open files) is a tool to view files op...

This article teaches you how to play with CSS border

Border Style The border-style property specifies ...

Let's talk about my understanding and application of React Context

Table of contents Preface First look at React Con...

Linux system prohibits remote login command of root account

ps: Here is how to disable remote login of root a...

MySQL whole table encryption solution keyring_file detailed explanation

illustrate MySql Community Edition supports table...

JS realizes video barrage effect

Use ES6 modular development and observer mode to ...

Solution to the problem of mysql master-slave switch canal

After configuring VIP, the error message that app...

Vue template configuration and webstorm code format specification settings

Table of contents 1. Compiler code format specifi...

About the problems of congruence and inequality, equality and inequality in JS

Table of contents Congruent and Incongruent congr...

Detailed examples of how to use the box-shadow property in CSS3

There are many attributes in CSS. Some attributes...

Detailed explanation of CSS3 to achieve responsive accordion effect

I recently watched a video of a foreign guy using...

First experience of creating text with javascript Three.js

Table of contents Effect Start creating text Firs...