5

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'
Chris
  • 1,236
  • 2
  • 18
  • 34
  • 1
    I use UniqID, to generate 8 and 12 bits longs ids https://www.npmjs.com/package/uniqid – Maxime Girou Aug 28 '19 at 06:19
  • 1
    8 and 12 bits? that's gonna run out quick :p – Jaromanda X Aug 28 '19 at 06:21
  • 2
    You do understand the chance of "collision" using only 32 bits it far greater than when using the 128 bits (ok, a few less) of a UUID? – Jaromanda X Aug 28 '19 at 06:22
  • 1
    if the UUID generation is not too quick(like in milliseconds) you can use timestamp `+new Date()` – Kaushik Aug 28 '19 at 06:31
  • 1
    An uuid contains 32 hex characters, thats 128bit of data. A String character can contain 16bit of data. So, let's format that differently: `'1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'.replace(/\W+/g, "").replace(/..../g, m => String.fromCharCode("0x"+m))` makes exactly 8 characters, still contains 128bit of data – Thomas Aug 28 '19 at 07:16

4 Answers4

9

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

Eric Aig
  • 972
  • 1
  • 13
  • 18
4

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");
ar4093
  • 141
  • 2
3

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

Brad
  • 159,648
  • 54
  • 349
  • 530
1

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

Rafat97
  • 25
  • 2
  • 8