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

Detailed analysis and usage of tcpdump command under Linux

Introduction To put it simply, tcpdump is a packe...

A brief discussion on the solution to excessive data in ElementUI el-select

Table of contents 1. Scenario Description 2. Solu...

MySQL Database Basics: A Summary of Basic Commands

Table of contents 1. Use help information 2. Crea...

Detailed explanation of mysql filtering replication ideas

Table of contents mysql filtered replication Impl...

MySQL-8.0.26 Configuration Graphics Tutorial

Preface: Recently, the company project changed th...

The difference between html block-level tags and inline tags

1. Block-level element: refers to the ability to e...

How to start multiple MySQL databases on a Linux host

Today, let’s talk about how to start four MySQL d...

Vue realizes the sliding cross effect of the ball

This article example shares the specific code of ...

In-depth understanding of Worker threads in Node.js

Table of contents Overview The history of CPU-bou...

HTML end tag issue and w3c standard

According to the principles of W3C, each start tag...

Solve the pitfall of storing boolean type values ​​in localstorage

LocalStorage stores Boolean values Today, when I ...

How to increase HTML page loading speed

(1) Reduce HTTP requests. (Merge resource files a...

Docker uses root to enter the container

First run the docker container Run the command as...