@rzl-zone/utils-js
Version:
A modern, lightweight set of JavaScript utility functions with TypeScript support for everyday development, crafted to enhance code readability and maintainability.
341 lines (332 loc) • 15.7 kB
TypeScript
/*!
* ====================================================
* Rzl Utils-JS.
* ----------------------------------------------------
* Version: 3.11.0.
* Author: Rizalvin Dwiky.
* Repository: https://github.com/rzl-zone/utils-js.
* ====================================================
*/
import { NullToUndefined, FixNeverArrayRecursive, IfNonEmptyArray, Extends } from '@rzl-zone/ts-types-plus';
/** ---------------------------------
* * ***Utility: `getRandomItem`.***
* ---------------------------------
* **Function to get a random element from a given array.**
* @template T - The type of the input array.
* @param {*} array - The input array, can be `null`, `undefined`, or an empty array.
* @returns
* - If `array` is a non-empty tuple, returns one of its elements.
* - If `array` is empty, `null`, or `undefined`, returns `undefined`.
* @example
* getRandomItem([]);
* // ➔ undefined
* getRandomItem(null);
* // ➔ undefined
* getRandomItem(undefined);
* // ➔ undefined
* getRandomItem([1, 2, 3, 4]);
* // ➔ number
* getRandomItem(["apple", "banana", "cherry"]);
* // ➔ string
* getRandomItem(["apple", 123, true]);
* // ➔ string | number | boolean
* getRandomItem(["apple", 123, true, null]);
* // ➔ string | number | boolean | undefined
* getRandomItem(["apple", 123, true, undefined]);
* // ➔ string | number | boolean | undefined
*
* // Tuple example:
* const tuple = [1, "two", true] as const;
* getRandomItem(tuple); // 1 | "two" | true
*/
declare function getRandomItem(array: undefined): undefined;
declare function getRandomItem(array: []): undefined;
declare function getRandomItem<T extends readonly unknown[]>(array: T): T extends never[][] ? undefined : number extends T["length"] ? NullToUndefined<FixNeverArrayRecursive<T[number]>> : IfNonEmptyArray<T, NullToUndefined<FixNeverArrayRecursive<T[number]>>, undefined>;
declare function getRandomItem<T extends readonly unknown[] | undefined | null>(array: T): T extends readonly unknown[] ? NullToUndefined<FixNeverArrayRecursive<T[number]>> | undefined : undefined;
declare function getRandomItem<T>(array: T): unknown extends T ? unknown : Extends<any[] | readonly any[], T> extends true ? Extract<T, unknown[] | readonly unknown[]>[number] | undefined : Extends<any[], T> extends true ? Extract<T, unknown[] | readonly unknown[]>[number] | undefined : Extends<readonly any[], T> extends true ? Extract<T, unknown[] | readonly unknown[]>[number] | undefined : undefined;
/** -----------------------------------------------------------------------
* * ***Utility: `randomInt`.***
* ------------------------------------------------------------------------
* **Generates a random integer within a specified range (inclusive).**
* - **Generates a random integer between `min` and `max` (inclusive), with safety constraints:**
* - `min` will be forced to be at least `1`.
* - `max` will be capped at `Number.MAX_SAFE_INTEGER`.
* @param {number} min - The minimum value (inclusive), must be an integer.
* @param {number} max - The maximum value (inclusive), must be an integer.
* @returns {number} A random integer N where `min ≤ N ≤ max`.
* @throws **{@link TypeError | `TypeError`}** if:
* - `min` or `max` is not an integer, or value is `Number.MIN_VALUE`.
* - `min` is greater than `max`.
* @example
* randomInt(1, 10); // ➔ returns 1 up-to 10 (random)
* randomInt(50, 100); // ➔ returns 50 up-to 100 (random)
* randomInt(5, 5); // ➔ always returns 5 (exact)
* randomInt(-5, 3); // ➔ always returns ≥ 1, since min is adjusted (exact)
* randomInt(1, Number.MAX_SAFE_INTEGER + 10000);
* // ➔ still safely capped at MAX_SAFE_INTEGER
* randomInt(Number.MIN_VALUE, 3);
* // ➔ Error, min or max cant be as `Number.MIN_VALUE` value.
*/
declare const randomInt: (min: number, max: number) => number;
type OptionsRandomIntByLength = {
/** * Minimum length of the random number, the `allowed minimal value` `integer` is `1` `and not bigger than value of` `maxLength`, defaultValue: `1`.
*
* @default 1
*/
minLength?: number;
/** * Maximum length of the random number, the `allowed maximal value` `integer` is `16`, defaultValue: `16`.
*
* @default 16
*/
maxLength?: number;
/** * If true, prevents the result from being zero, defaultValue: `false`.
*
* @default false
*/
avoidZero?: boolean;
};
/** ----------------------------------------------------------------------------
* * ***Utility: `randomIntByLength`.***
* -----------------------------------------------------------------------------
* **Generates a random integer within a specified range of digit lengths.**
* @description
* This function allows generating random integers that strictly conform to a specified minimum and
* maximum digit length, it is useful for scenarios such as generating realistic-looking IDs, codes,
* or random test data.
* - **The function ensures:**
* - `minLength` is at least 1 and not greater than `maxLength`.
* - `maxLength` is no more than 16 (due to JavaScript's `Number.MAX_SAFE_INTEGER`).
* - If `avoidZero` is `true`, ensures that `0` is never returned.
* @param {OptionsRandomIntByLength} [options] - Configuration options.
* @param {OptionsRandomIntByLength["minLength"]} [options.minLength=1] - Minimum number of digits (must be ≥ `1` and ≤ `maxLength`).
* @param {OptionsRandomIntByLength["maxLength"]} [options.maxLength=16] - Maximum number of digits (must be ≤ `16`).
* @param {OptionsRandomIntByLength["avoidZero"]} [options.avoidZero=false] - If true, will ensure the result is never zero.
* @returns {number} A randomly generated integer within the specified constraints.
* @throws **{@link TypeError | `TypeError`}** if parameters are invalid, such as:
* - `minLength` < `1`
* - `maxLength` > `16`
* - `minLength` > `maxLength`
* - non-integer values for `minLength` or `maxLength`
* @example
* randomIntByLength({ minLength: 3, maxLength: 5 });
* // ➔ `4829` (random), `192` (random) or `71492` (random).
* randomIntByLength({ minLength: 4, maxLength: 4 });
* // ➔ `5930` (exact 4 digits)
* randomIntByLength({ avoidZero: true });
* // ➔ never 0
*/
declare const randomIntByLength: (options?: OptionsRandomIntByLength) => number;
type OptionsRandomStr = {
/** ***Ensures no whitespace characters in the generated string, defaultValue: `true`.***
* @default true
*/
avoidWhiteSpace?: boolean;
/** ***Custom characters to replace the default number set if `type` is `"number"`, defaultValue: `undefined`.***
* @default undefined
*/
replaceGenInt?: string;
/** ***Custom characters to replace the default string set if `type` is `"string"`, defaultValue: `undefined`.***
* @default undefined
*/
replaceGenStr?: string;
/** ***Additional characters to include in the generated string, defaultValue: `undefined`.***
* @default undefined
*/
addChar?: string;
/** ***Minimum length of the generated string (1 to 5000), defaultValue: `40`.***
* @default 40
*/
minLength?: number;
/** ***Maximum length of the generated string (1 to 5000), defaultValue: `40`.***
* @default 40
*/
maxLength?: number;
/** ***Type of output: `"string"` or `"number"`, defaultValue: `"string"`.***
* @default "string"
*/
type?: "string" | "number";
};
/** ---------------------------------------------------------------------------------
* * ***Utility: `randomStr`.***
* ---------------------------------------------------------------------------------
* **Generates a random alphanumeric string or number with a specified length range.**
* @description
* This function allows you to generate random strings or numbers with fully
* customizable options, such as length range, character sets, inclusion of
* additional characters, and whether to avoid whitespace.
* @param {OptionsRandomStr} [options] - Configuration options for generating the string.
* @param {OptionsRandomStr["minLength"]} [options.minLength=40] - Minimum length of the generated string (must be `≥` `1`).
* @param {OptionsRandomStr["maxLength"]} [options.maxLength=40] - Maximum length of the generated string (must be `≤` `5000`).
* @param {OptionsRandomStr["type"]} [options.type="string"] - Whether to generate a general alphanumeric string or purely numeric string.
* @param {OptionsRandomStr["avoidWhiteSpace"]} [options.avoidWhiteSpace=true] - If true, removes all whitespace, tabs, and newlines from the character set before generating.
* @param {OptionsRandomStr["replaceGenStr"]} [options.replaceGenStr] - A custom character set to use when `type` is `"string"`.
* @param {OptionsRandomStr["replaceGenInt"]} [options.replaceGenInt] - A custom character set to use when `type` is `"number"`.
* @param {OptionsRandomStr["addChar"]} [options.addChar] - Additional characters to always include in the character set.
* @returns {string} The randomly generated string or numeric string of the desired length.
* @throws **{@link TypeError | `TypeError`}** if provided options are invalid (such as minLength > maxLength, invalid type, or empty character set).
* @example
* randomStr();
* // ➔ Generates a 40-character random alphanumeric string
* randomStr({ minLength: 10, maxLength: 20 });
* // ➔ Generates a string between 10 and 20 characters
* randomStr({ type: "number", minLength: 5, maxLength: 5 });
* // ➔ "48302"
* randomStr({ replaceGenStr: "ABC ", avoidWhiteSpace: false });
* // ➔ String using A, B, C and space
* randomStr({ addChar: "!@#", minLength: 15, maxLength: 15 });
* // ➔ Guaranteed to include !@# in the set
*/
declare const randomStr: (options?: OptionsRandomStr) => string;
/**
* Configuration options for `randomUUID()`.
*/
type OptionsRandomUUID = {
/**
* Specifies which UUID version to generate.
*
* - `"v4"` — Fully random UUID (RFC 4122). No timestamp, no ordering guarantees.
* - `"v7"` — Time-ordered UUID (RFC 9562). Uses Unix timestamp + randomness.
*
* @default "v4"
*
* @example
* // Random v4 UUID
* randomUUID({ version: "v4" }); // ➔ "3ec0de5a-b8a9-4ffb-a62a-fcc76851e9c2"
*
* @example
* // Time-ordered v7 UUID
* randomUUID({ version: "v7" }); // ➔ "0199f3f6-3c5e-744b-affa-46b2cfd496f8"
*/
version?: "v4" | "v7";
/**
* Enables monotonic sequencing for UUID v7.
*
* - Guarantees that multiple UUIDs generated within the same millisecond
* are strictly non-decreasing (lexicographically and timestamp-wise).
* - Only valid when `version === "v7"`. Using with `v4` will throw a `TypeError`.
* - Useful for database inserts, logs, or any system where order matters.
*
* @default false
*
* @example
* // Monotonic v7 UUIDs
* const a = randomUUID({ version: "v7", monotonic: true });
* const b = randomUUID({ version: "v7", monotonic: true });
* console.log(a < b); // true, guaranteed
*/
monotonic?: boolean;
};
/** -----------------------------------------------------------------------
* * ***Utility: `randomUUID`.***
* ------------------------------------------------------------------------
* **Generates a UUID string according to the specified version and options.**
*
* - **Supported versions**:
* - **`"v4"` (default)** ➔ Fully random UUID, RFC 4122 compliant.
* - Uses `crypto.randomUUID()` if available.
* - Falls back to `crypto.getRandomValues()` or `Math.random()`
* if needed.
* - **`"v7"`** ➔ Time-ordered UUID, RFC 9562 compliant.
* - Timestamp (Unix ms, 48 bits) + 80 bits randomness.
* - Good for database indexing / sorting.
* - **`"v7"` + `monotonic: true`** ➔ Ensures strictly non-decreasing UUIDs
* for multiple calls in the same millisecond (per-process).
*
* - **Behavior / Safety Notes**:
* - **v4**: Fully random; probability of duplicates is astronomically low.
* - **v7**: Time-ordered; collisions extremely unlikely unless same ms + random repeat.
* - **Monotonic v7**: Guaranteed ordering per-process if multiple UUIDs are generated
* in the same millisecond.
* - **All versions**: Fallback safely if `crypto` APIs are unavailable.
*
* @param {object} [options] - Optional settings object.
* @param {"v4" | "v7"} [options.version="v4"] - UUID version to generate.
* @param {boolean} [options.monotonic=false] - For v7 only: generate monotonic UUIDs
* to maintain strict lexicographic order
* when generating multiple UUIDs within the same ms.
*
* @returns {string} A 36-character UUID string compliant with the selected version.
*
* @throws **{@link TypeError | `TypeError`}** if:
* - `options` is not a plain object.
* - `options.version` is provided but not a string.
* - `options.monotonic` is provided but not a boolean.
* - `monotonic: true` is used with `version` other than `"v7"`.
* @throws **{@link RangeError | `RangeError`}** if `options.version` is provided but not `"v4"` or `"v7"`.
*
* @example
* // Default (v4)
* const id = randomUUID();
* // ➔ "3b12f1df-5232-4804-897e-917bf397618a"
*
* @example
* // Explicit v4
* const id4 = randomUUID({ version: "v4" });
*
* @example
* // Time-ordered v7
* const id7 = randomUUID({ version: "v7" });
* // ➔ "018f48d2-84c1-7ccd-b5a3-2f9463b3a889"
*
* @example
* // Monotonic v7
* const a = randomUUID({ version: "v7", monotonic: true });
* const b = randomUUID({ version: "v7", monotonic: true });
* // a < b lexicographically (guaranteed)
*
* @example
* // Throws TypeError
* randomUUID("v4" as any); // options must be object
* randomUUID({ version: 123 as any }); // version must be string
* randomUUID({ version: "v4", monotonic: true } as any); // monotonic only for v7
*
* @example
* // Throws RangeError
* randomUUID({ version: "v1" as any }); // unsupported version
*/
declare function randomUUID(options?: OptionsRandomUUID): string;
/**
* --------------------------------------------------
* * ***Utility: `noop`.***
* --------------------------------------------------
* **A no-operation function that performs no action.**
*
* @description
* Commonly used as a **placeholder**, **default callback**, or **stub function**.
*
* - **Behavior**:
* - Does not return any meaningful value (`void`).
* - Safely callable in any context without side effects.
*
* @remarks
* Although this function returns `void`, it implicitly results in `undefined`,
* but the return value should never be relied upon.
*
* @example
* **1. Basic usage** — does nothing and returns undefined implicitly:
* ```
* import { noop } from "@rzl-zone/utils-js/generators";
*
* noop(); // ➔ no effect (void)
* ```
* @example
* **2. Using with type-checking helpers:**
* ```ts
* import { noop } from "@rzl-zone/utils-js/generators";
* import { isFunction, isUndefined } from "@rzl-zone/utils-js/predicates";
*
* isFunction(noop); // ➔ true — `noop` is a function
* isUndefined(noop()); // ➔ true — calling `noop()` returns `undefined`
* isFunction(noop()); // ➔ false — the return value is `undefined`, not a function
* ```
* @example
* **3. As a default callback:**
* ```ts
* import { noop } from "@rzl-zone/utils-js/generators";
*
* const callback = noop;
* callback(); // ➔ no effect (void)
* ```
*/
declare const noop: () => void;
export { getRandomItem, noop, randomInt, randomIntByLength, randomStr, randomUUID };