@xiping/random
v1.0.97
Published
CSPRNG utilities for browser and Node (crypto.getRandomValues)
Readme
@xiping/random
基于 Web Crypto getRandomValues 的 CSPRNG 工具集,浏览器与 Node 均可使用。
环境缺少 crypto.getRandomValues 时直接抛错,不会回退到 Math.random。
安装
pnpm add @xiping/random特性
- 密码学安全随机源(CSPRNG)
randomInt/randomString使用拒绝采样,避免取模偏差randomFloat使用 53-bit 精度,对齐Number- 抽取 / 洗牌均返回新数组,不修改入参
- 零依赖
用法
import {
randomBytes,
randomInt,
randomFloat,
randomUUID,
randomPick,
randomPicks,
shuffle,
randomString,
} from '@xiping/random';
randomBytes(16); // Uint8Array(16)
randomInt(0, 100); // [0, 100)
randomFloat(); // [0, 1)
randomFloat(1, 10); // [1, 10)
randomUUID(); // UUID v4
randomPick(['a', 'b', 'c']); // 均匀选 1 项
randomPicks(['a', 'b', 'c', 'd'], 2); // 无放回抽 2 项
shuffle([1, 2, 3]); // 新数组,原数组不变
randomString(16); // 默认 A–Z a–z 0–9
randomString(8, '01'); // 自定义字符集API
| 函数 | 说明 | 约束 |
|------|------|------|
| randomBytes(length) | 返回 Uint8Array | length 为非负整数 |
| randomInt(min, max) | 无偏整数,区间 [min, max) | min/max 为有限整数;min < max;max - min ≤ 2^32 |
| randomFloat(min?, max?) | 浮点数,默认 [0, 1) | min/max 有限;min < max |
| randomUUID() | UUID v4 字符串 | 优先 crypto.randomUUID,否则自行生成 |
| randomPick(array) | 均匀选一项 | 数组不可为空 |
| randomPicks(array, n) | 无放回均匀抽 n 项,返回新数组 | 0 ≤ n ≤ array.length;同一下标不会抽两次 |
| shuffle(array) | Fisher–Yates 洗牌,返回新数组 | — |
| randomString(length, alphabet?) | 随机字符串;默认字母数字 | length ≥ 0;alphabet 非空且长度 ≤ 256 |
说明
- 所有函数依赖
globalThis.crypto.getRandomValues。 randomPicks保证下标不重复;若原数组本身含重复值,结果中仍可能出现相同值。shuffle/randomPicks均为浅拷贝后的新数组,不会原地修改入参。
