UNPKG

@alwatr/random

Version:

A lightweight utility library for generating random numbers, strings, UUIDs and more

98 lines (96 loc) 2.84 kB
/* @alwatr/random v5.1.2 */ // src/main.ts import { getGlobalThis } from "@alwatr/global-this"; import { packageTracer } from "@alwatr/package-tracer"; var globalThis = getGlobalThis(); __dev_mode__: packageTracer.add("@alwatr/random", "5.1.2"); var hasCrypto = typeof globalThis.crypto !== "undefined"; function bytesToHex(bytes) { let result = ""; for (const byte of bytes) { const hex = byte.toString(16); result += hex.length === 1 ? "0" + hex : hex; } return result; } function randNumber() { return Math.random(); } function randFloat(min, max) { return Math.random() * (max - min) + min; } function randInteger(min, max) { return Math.floor(randFloat(min, max + 1)); } function randString(minLength, maxLength = minLength, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") { const length = maxLength === minLength ? minLength : randInteger(minLength, maxLength); if (length <= 0) return ""; const charsLength = chars.length; let result = ""; if (length <= 10) { for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * charsLength)); } return result; } const resultArray = new Array(length); for (let i = 0; i < length; i++) { resultArray[i] = chars.charAt(Math.floor(Math.random() * charsLength)); } return resultArray.join(""); } function randStep(min, max, step) { if (step === 0) { return min; } const steps = Math.floor((max - min) / step); return min + randInteger(0, steps) * step; } function randShuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = randInteger(0, i); [array[i], array[j]] = [array[j], array[i]]; } return array; } function randPick(array) { if (array.length === 0) throw new Error("Cannot pick from empty array"); return array[randInteger(0, array.length - 1)]; } function randArray(array, min = 0, max = 255) { for (let i = array.length - 1; i >= 0; i--) { array[i] = randInteger(min, max); } return array; } function randUuid() { if (hasCrypto && globalThis.crypto?.randomUUID) { return globalThis.crypto.randomUUID(); } const bytes = randArray(new Uint8Array(16)); bytes[6] = bytes[6] & 15 | 64; bytes[8] = bytes[8] & 191 | 128; return `${bytesToHex(bytes.subarray(0, 4))}-${bytesToHex(bytes.subarray(4, 6))}-${bytesToHex(bytes.subarray(6, 8))}-${bytesToHex(bytes.subarray(8, 10))}-${bytesToHex(bytes.subarray(10, 16))}`; } function randBoolean(probability = 0.5) { return Math.random() < probability; } function randColor() { const bytes = randArray(new Array(3)); return `#${bytesToHex(bytes)}`; } export { bytesToHex, randArray, randBoolean, randColor, randFloat, randInteger, randNumber, randPick, randShuffle, randStep, randString, randUuid }; //# sourceMappingURL=main.mjs.map