UNPKG

shuffrand

Version:

Cryptographically secure randomness and shuffling — with soul.

32 lines (31 loc) 1.96 kB
/** * Shuffles an array using the cryptographically secure Fisher–Yates algorithm. * Wikipedia.org/wiki/Fisher–Yates_shuffle * * @template T - The type of elements in the array. * @param {T[]} [arr=[]] - The array to shuffle. Defaults to an empty array if omitted. * @param {object} [options={}] - Optional parameters for shuffling. * @param {boolean} [options.isDestructive=false] - Whether to shuffle the array in place (destructive) or create a new shuffled array (non-destructive). * @param {boolean} [options.preventIdentical=false] - If true, and the initial shuffle results in an array identical to the original input, * the first and last elements will be swapped to guarantee a different result. * This introduces a statistical bias by excluding the original permutation. Do not use in cryptographic or * fairness-critical contexts where absolute unbiased randomness is required. * @param {number} [options.startIndex=0] - The starting index of the subarray to shuffle (inclusive). * Defaults to 0, shuffling from the beginning of the array. * Must be a non-negative integer within the array bounds. * If greater than or equal to `endIndex`, no shuffling occurs on the subarray. * @param {number} [options.endIndex=arr.length] - The ending index of the subarray to shuffle (exclusive). * Defaults to the array's length, shuffling to the end of the array. * Must be a non-negative integer within the array bounds (0 to arr.length). * If less than or equal to `startIndex`, no shuffling occurs on the subarray. * @returns {T[]} - The shuffled array. * @throws {TypeError} - If input parameters do not conform to the schema or if array serialization fails. * @since 1.0.0 * @since 1.6.0 Added `startIndex` and `endIndex` for subarray shuffling. */ export declare function cryptoShuffle<T>(arr?: T[], options?: { isDestructive?: boolean; preventIdentical?: boolean; startIndex?: number; endIndex?: number; }): T[];