( array: Array<T>, seed: number )
| 1 | // Fisher-Yates shuffle algorithm with a seed for deterministic results |
| 2 | export const shuffle = async <T>( |
| 3 | array: Array<T>, |
| 4 | seed: number |
| 5 | ): Promise<Array<T>> => { |
| 6 | const shuffled = [...array]; |
| 7 | const encoder = new TextEncoder(); |
| 8 | const buffer = encoder.encode(String(seed)); |
| 9 | const hashBuffer = await crypto.subtle.digest('SHA-256', buffer); |
| 10 | const hash = new Uint8Array(hashBuffer); |
| 11 | |
| 12 | for (let i = shuffled.length - 1; i > 0; i--) { |
| 13 | // Use hash bytes to generate deterministic "random" index |
| 14 | const hashIndex = (i + seed) % 32; |
| 15 | // Normalize to 0-1 |
| 16 | const randomValue = hash[hashIndex] / 255; |
| 17 | |
| 18 | const j = Math.floor(randomValue * (i + 1)); |
| 19 | [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; |
| 20 | } |
| 21 | |
| 22 | return shuffled; |
| 23 | }; |
no outgoing calls
no test coverage detected