UUID Wand
UUID Wand is a TypeScript library that provides functionality to generate and validate UUIDs (Universally Unique Identifiers).
Docs
Table of Contents
Installation
To use this library in your project, make sure you have Node.js installed. Follow the steps below to install and use the library:
-
Clone the repository or download the source code files.
-
Install the required dependencies by running the following command in the project directory:
npm install uuid-wand
yarn add uuid-wand
pnpm add uuid-wand
-
Import the UuidGenerator
class into your TypeScript file:
import UuidGenerator from 'uuid-wand';
Usage
Generating UUIDs
The UuidGenerator
class provides four methods for generating UUIDs:
-
v1()
: Generates a version 1 UUID using the current timestamp, clock sequence, and node ID.
const uuidV1 = UuidGenerator.v1();
console.log(uuidV1);
-
v3(namespace: string, name: string)
: Generates a version 3 UUID using the provided namespace and name.
const uuidV3 = UuidGenerator.v3(
'6ba7b810-9dad-11d1-80b4-00c04fd430c8',
'Hello, World!',
);
console.log(uuidV3);
-
v4()
: Generates a version 4 UUID using random values.
const uuidV4 = UuidGenerator.v4();
console.log(uuidV4);
-
v5(namespace: string, name: string)
: Generates a version 5 UUID using the provided namespace and name.
const uuidV5 = UuidGenerator.v5(
'6ba7b811-9dad-11d1-80b4-00c04fd430c8',
'Hello, World!',
);
console.log(uuidV5);
Validating UUIDs
- The
validate()
method can be used to check if a given string is a valid UUID.
const uuid = '6a365c44-e127-11eb-b95f-cb258f9664de';
const isValid = UuidGenerator.validate(uuid);
console.log(isValid);
Bulk Generation
- The method bulkGenerateV4 takes an integer count as an argument and returns an array of version 4 UUIDs.
const uuids = UuidGenerator.bulkGenerateV4(5);
console.log(uuids);
Timestamp Retrieval
- The method extractTimestampV1 extracts the timestamp from a version 1 UUID string. It returns the timestamp as a number or null if the UUID is not valid or not a version 1 UUID. The extraction logic relies on bit manipulation and should be fairly efficient.
const uuid = '6a365c44-e127-11eb-b95f-cb258f9664de';
const timestamp = UuidGenerator.extractTimestampV1(uuid);
console.log(timestamp);
Short UUID
- The method shortUuid creates a shorter, URL-friendly UUID by generating a version 4 UUID, hashing it with MD5, and then encoding it using base64. Any characters not safe for URLs are replaced.
const shortUuid = UuidGenerator.shortUuid();
console.log(shortUuid);
License
This library is released under the MIT License. Feel free to modify and use it in your projects.