MCPcopy Create free account
hub / github.com/nodejs/nodejs.org / shuffle

Function shuffle

apps/site/util/array.ts:2–23  ·  view source on GitHub ↗
(
  array: Array<T>,
  seed: number
)

Source from the content-addressed store, hash-verified

1// Fisher-Yates shuffle algorithm with a seed for deterministic results
2export 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};

Callers 2

sponsorsDataFunction · 0.90
generatePartnersFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected