Chris
Chris

Reputation: 1304

Alternative for UUID

I am using UUIDto generate random codes. But It's returning me 20+ digits. Is there is any other algorithm mechanism that returns 8-digit code that is unique or any other way to reduce UUID code length.

Code

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

Upvotes: 7

Views: 13892

Answers (4)

Rafat97
Rafat97

Reputation: 35

You can try ULID. It is a Universally Unique Lexicographically Sortable Identifier.

Upvotes: 2

Eric Aig
Eric Aig

Reputation: 1084

You could try nanoid out.

It's smaller in size compared to UUID, faster and generates shorter unique codes.

    import { nanoid } from 'nanoid'
    model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"

Read more of it here: https://github.com/ai/nanoid

Upvotes: 9

ar4093
ar4093

Reputation: 141

For random strings of any size, as well as applications that need "stronger" random strings/numbers, you can use the crypto module.

For example, if you want 8 hexadecimal characters (= 4 bytes), you could use

const crypto = require("crypto");

var randomHexString = crypto.randomBytes(4).toString("hex");

you can use other characters sets too, for example if you want 8 random Base 64 characters (= 6 bytes):

const crypto = require("crypto");

var randomB64String = crypto.randomBytes(6).toString("base64");

Upvotes: 4

Brad
Brad

Reputation: 163334

For v4 UUIDs, those first 4 bytes are random. So, if you wanted, you could take the first 4 bytes (8 characters of hexadecimal), and use them as-is.

Keep in mind though that the UUID is designed to avoid collisions. If you too want to avoid collisions, you should just use UUID as-is.

Another way to reduce its character length is to use some other encoding rather than hexadecimal. You could use Base-64, for example. See also: https://stackoverflow.com/a/15013205/362536

Upvotes: 3

Related Questions