shuffrand
Version:
Cryptographically secure randomness and shuffling — with soul.
10 lines (9 loc) • 2.82 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./types.cjs.js"),x=require("./random.cjs.js");/**
* shuffrand - Cryptographically Secure Array Shuffling
*
* This file contains the core logic for shuffling arrays using a cryptographically secure method,
* adhering to a flat, dot-categorized structure for clarity.
*
* @author Doron Brayer <doronbrayer@outlook.com>
* @license MIT
*/function v(m=[],e={}){if(e===null)throw new TypeError("Invalid cryptoShuffle parameters: 'options' cannot be null. Please provide an object or omit it.");if(e.startIndex!==void 0){if(typeof e.startIndex!="number")throw new TypeError(`Invalid cryptoShuffle parameters: startIndex must be a number (was ${typeof e.startIndex})`);if(!Number.isInteger(e.startIndex))throw new TypeError(`Invalid cryptoShuffle parameters: startIndex must be an integer (was ${e.startIndex})`)}if(e.endIndex!==void 0){if(typeof e.endIndex!="number")throw new TypeError(`Invalid cryptoShuffle parameters: endIndex must be a number (was ${typeof e.endIndex})`);if(!Number.isInteger(e.endIndex))throw new TypeError(`Invalid cryptoShuffle parameters: endIndex must be an integer (was ${e.endIndex})`)}const n={arr:m,isDestructive:e.isDestructive??!1,preventIdentical:e.preventIdentical??!1,startIndex:e.startIndex,endIndex:e.endIndex};let o;try{p.shuffleParamsSchema.assert(n),o={arr:n.arr??[],isDestructive:n.isDestructive??!1,preventIdentical:n.preventIdentical??!1,startIndex:n.startIndex??0,endIndex:n.endIndex??n.arr?.length??0}}catch(r){throw new TypeError(`Invalid cryptoShuffle parameters: ${r.summary||r.message}`)}const{arr:s,isDestructive:y,preventIdentical:I,startIndex:l,endIndex:d}=o,i=s.length;if(l<0||l>i)throw new TypeError(`Invalid cryptoShuffle parameters: 'startIndex' (${l}) must be between 0 and the array length (${i}), inclusive.`);if(d<0||d>i)throw new TypeError(`Invalid cryptoShuffle parameters: 'endIndex' (${d}) must be between 0 and the array length (${i}), inclusive.`);const t=y?s:[...s],a=t.length,u=Math.max(0,Math.min(l,a)),h=Math.max(u,Math.min(d,a));let c=null;if(I)try{c=JSON.stringify(s)}catch(r){throw new TypeError(`Invalid cryptoShuffle parameters: Array elements cannot be serialized for 'preventIdentical' comparison. Ensure all elements are JSON-serializable. Original error: ${r.message}`)}for(let r=h-1;r>u;r--){const f=x.cryptoRandom({lowerBound:u,upperBound:r,typeOfNum:"integer",exclusion:"none"});[t[r],t[f]]=[t[f],t[r]]}if(I&&c!==null&&a>1){let r;try{r=JSON.stringify(t)}catch(f){throw new TypeError(`Invalid cryptoShuffle parameters: Shuffled array elements cannot be serialized for 'preventIdentical' comparison. Ensure all elements are JSON-serializable. Original error: ${f.message}`)}r===c&&([t[0],t[a-1]]=[t[a-1],t[0]])}return t}exports.cryptoShuffle=v;