react-native-uuid

repository·master·Indexed 43 days ago

https://github.com/eugenehp/react-native-uuid

A zero-dependency TypeScript implementation of RFC4122 for generating secure and collision-resistant UUIDs in React Native and Node.js environments. Version 2.0.4 supports v1 (time-based), v3 (MD5 name-based), v4 (random), and v5 (SHA-1 name-based) UUIDs, along with utilities for parsing, stringifying, and hashing.

Tokens
8.9K
Snippets
44
Records
50
Agent score
54%

What's inside react-native-uuid

  1. Generate a Version 1 (Time-based) UUID

    master

    Understanding the internal data flow can help when debugging or extending the library.

    UUID v4 Generation Flow

    1. RNG: Get the Random Number Generator (default or custom).
    2. Bytes: Generate 16 random bytes.
    3. Version Bits: Set version bits (010 in the time_hi_and_version field).
    4. Variant Bits: Set variant bits (10 in the clock_seq_hi_and_reserved field).
    5. Stringify: Convert bytes to hex and format as xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx.

    UUID v5 (Name-based) Flow

    1. Parse: Parse the namespace UUID into bytes.
    2. Combine: Combine namespace bytes with the name string.
    3. Hash: Hash the combined data using SHA1.
    4. Stringify: Call stringify() with version=5 and variant=10 bits set.
    import { version } from 'react-native-uuid';
    
    const id = 'f47ac10b-58cc-4372-a567-0e02b2c3d479';
    const v = version(id);
    console.log(v); // 4
  2. Import and use react-native-uuid

    master

    You can use react-native-uuid by either using the default export for a unified interface or by importing specific versioned generators as named exports. This allows for a clean, modular approach to UUID generation in your React Native or Node.js projects.

    Usage Patterns:

    • Default Export: Access all methods via a single object (e.g., uuid.v4()).
    • Named Exports: Import only the specific version you need (e.g., import { v4 } from 'react-native-uuid').
    // Using default export
    import uuid from 'react-native-uuid';
    const id = uuid.v4();
    
    // Using named exports
    import { v4 } from 'react-native-uuid';
    const id = v4();
  3. Use the react-native-uuid default export

    master

    The default export of the react-native-uuid module provides a comprehensive suite of UUID generation and manipulation utilities. It includes version-specific generators (v1, v3, v4, v5), validation tools, and parsing/unparsing capabilities for different UUID formats.

    import uuid from 'react-native-uuid';
    
    // Example usage of available properties:
    const id = uuid.v4();
    const isValid = uuid.validate(id);
    const version = uuid.version(id);
  4. Parse a UUID string using parse()

    master

    The parse function converts a UUID string into an array of numbers (bytes). This is useful when you need to work with the raw byte representation of a UUID instead of its string format.

    Parameters:

    • s: The UUID string to be parsed.
    • buf (optional): An existing number[] array to store the parsed bytes. If provided, the function will write into this buffer.
    • offset (optional): The starting index in buf where the parsed bytes should be written.

    Returns:

    • A number[] containing the byte representation of the UUID.
    // Basic usage
    const bytes = parse('550e8400-e29b-41d4-a716-446655440000');
  5. Generate deterministic UUIDs with v5()

    master

    The v5 function generates a name-based UUID using the SHA-1 hashing algorithm. Unlike random UUIDs (like v4), v5 UUIDs are deterministic: providing the same value and namespace will always produce the same UUID. This is useful for creating unique identifiers based on existing data (e.g., a user ID or an email address).

    import uuid from 'react-native-uuid';
    
    // Example usage:
    // Note: The namespace must be a valid UUID string or a byte array.
    const namespace = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; // DNS namespace
    const name = 'example.com';
    
    const id = uuid.v5(name, namespace);
    console.log(id); // Always returns the same UUID for these inputs
  6. Use the `default` regex variable

    master

    The regex module exports a default constant of type RegExp. This regular expression is used internally by the library for pattern matching and validation during UUID generation or parsing processes.

    import { default as uuidRegex } from 'react-native-uuid/regex';
    
    // uuidRegex is a RegExp instance used for UUID pattern matching
    const isValid = uuidRegex.test(someUuidString);
  7. Validate a UUID string with validate()

    master

    Use the validate function to check if a given string is a valid UUID. It returns true if the string conforms to the UUID format, and false otherwise.

    import { validate } from 'react-native-uuid';
    
    const isValid = validate('123e4567-e89b-12d3-a456-426614174000'); // true
    const isInvalid = validate('not-a-uuid'); // false
  8. Use the v35 module to generate UUIDs

    master

    The v35 module provides a way to generate UUIDs following the version 3 (MD5-based) specification. It is initialized by providing a name, a version number, and a hashing function. Once initialized, it returns a GenerateUUID function that can be used to create UUIDs based on a specific value and namespace.

    Note: The v35 function itself is a factory that returns the actual generator function.

    // Example of how the v35 factory and GenerateUUID function are structured
    // Note: Actual implementation requires providing a name, version, and hash function
    const generate = v35('example-name', 3, (s) => md5(s));
    const uuid = generate('my-value', 'my-namespace');
  9. Use the unparse function to convert byte arrays to strings

    master

    The unparse function converts an array of numbers (representing bytes) into a string. This is typically used to reconstruct a string representation from a raw buffer or byte array.

    Parameters:

    • buf: An array of numbers (number[]) representing the byte data.
    • offset?: An optional number representing the starting index in the buffer from which to begin unparsing.
    // Example usage (signature based on documentation)
    const result = unparse([0x68, 0x65, 0x6c, 0x6c, 0x6f]); // returns "hello"
  10. Convert Uint8Array to string using stringify()

    master

    The stringify function converts a Uint8Array into its string representation. It allows you to specify an optional offset to start the conversion from a specific index within the array.

    // Signature:
    // const stringify(arr: Uint8Array, offset?: number): string
    
    const result = stringify(myUint8Array, 0);
  11. Generate a v3 UUID

    master

    The v3 function generates a name-based UUID using the MD5 hashing algorithm. It requires a value (the name to hash) and a namespace (the UUID namespace to use). This is useful when you need to generate the same UUID every time for a specific input and namespace.

    // Example usage of v3
    // Note: Actual implementation requires importing 'v3' from 'react-native-uuid'
    const uuid = v3('my-name-value', '6ba7b810-9dad-11d1-80b4-00c04fd430c8');
  12. Generate a UUID v4

    master

    Use the v4 function to generate a version 4 UUID. This function can return either a formatted string or a raw number[] (byte array) depending on the arguments provided.

    Parameters

    • options? (string | V4Options): Configuration for the generator. If a string is provided, it is treated as a configuration option.
    • buf? (number[]): An optional buffer of numbers to be used or populated.
    • offset? (number): An optional offset for the buffer operations.

    Return Values

    • Returns a string (the standard UUID format) by default.
    • Returns a number[] if a buffer is provided.
    import { v4 } from 'react-native-uuid';
    
    // Default usage: returns a UUID string
    const uuid = v4();
    console.log(uuid); // e.g., 'f47ac10b-58cc-4372-a567-0e02b2c3d479'