|
| 1 | +class RandomPool { |
| 2 | + SIZE = 256; |
| 3 | + |
| 4 | + constructor() { |
| 5 | + this._rArray = new Uint8Array(this.SIZE); |
| 6 | + this._idx = this.SIZE; // Fill the pool on first use. |
| 7 | + } |
| 8 | + |
| 9 | + getValue() { |
| 10 | + if (this._idx > this.SIZE - 1) { |
| 11 | + // Fill the pool. |
| 12 | + globalThis.crypto.getRandomValues(this._rArray); |
| 13 | + this._idx = 0; |
| 14 | + } |
| 15 | + |
| 16 | + return this._rArray[this._idx++]; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const pool = new RandomPool(); |
| 21 | + |
| 22 | +/** |
| 23 | + * Choose `num` elements from `seq`, randomly. |
| 24 | + * |
| 25 | + * @param {string} seq - Sequence of characters, the alphabet. |
| 26 | + * @param {number} num - The amount of characters from the alphabet we want. |
| 27 | + * @returns {string} |
| 28 | + */ |
| 29 | +function randomChoice(seq, num) { |
| 30 | + const x = seq.length - 1; |
| 31 | + const r = new Array(num); |
| 32 | + |
| 33 | + while (num--) { |
| 34 | + // Make sure the random value is in our alphabet's range. |
| 35 | + const idx = pool.getValue() & x; |
| 36 | + |
| 37 | + r.push(seq[idx]); |
| 38 | + } |
| 39 | + |
| 40 | + return r.join(''); |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * This alphabet removes all potential ambiguous symbols, so it's well suited for a code. |
| 45 | + */ |
| 46 | +const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; |
| 47 | + |
1 | 48 | /** |
2 | 49 | * A method to generate a random string, intended to be used to create a random join code. |
3 | 50 | * |
4 | 51 | * @param {number} length - The desired length of the random string. |
5 | 52 | * @returns {string} |
6 | 53 | */ |
7 | 54 | export function generateRandomString(length) { |
8 | | - // XXX the method may not always give desired length above 9 |
9 | | - return Math.random() |
10 | | - .toString(36) |
11 | | - .slice(2, 2 + length); |
| 55 | + return randomChoice(BASE32, length); |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * This alphabet is similar to BASE32 above, but includes lowercase characters too. |
| 60 | + */ |
| 61 | +const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; |
| 62 | + |
| 63 | +/** |
| 64 | + * Generates a random 8 character long string. |
| 65 | + * |
| 66 | + * @returns {string} |
| 67 | + */ |
| 68 | +export function generate8Characters() { |
| 69 | + return randomChoice(BASE58, 8); |
12 | 70 | } |
0 commit comments