Skip to content

Commit 4c2d6cb

Browse files
committed
refactor: move shuffle util into the array utils
1 parent 3e007d7 commit 4c2d6cb

File tree

2 files changed

+27
-28
lines changed

2 files changed

+27
-28
lines changed

apps/site/components/Common/Partners/utils.ts

Lines changed: 2 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,5 @@
1-
import type {
2-
RandomPartnerListConfig,
3-
Partners,
4-
} from '#site/types/partners.js';
5-
6-
// Fisher-Yates shuffle algorithm with a seed for deterministic results
7-
async function shuffle(
8-
array: Array<Partners>,
9-
seed: number
10-
): Promise<Array<Partners>> {
11-
const shuffled = [...array];
12-
const encoder = new TextEncoder();
13-
const buffer = encoder.encode(String(seed));
14-
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
15-
const hash = new Uint8Array(hashBuffer);
16-
17-
for (let i = shuffled.length - 1; i > 0; i--) {
18-
// Use hash bytes to generate deterministic "random" index
19-
const hashIndex = (i + seed) % 32;
20-
// Normalize to 0-1
21-
const randomValue = hash[hashIndex] / 255;
22-
23-
const j = Math.floor(randomValue * (i + 1));
24-
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
25-
}
26-
27-
return shuffled;
28-
}
1+
import type { RandomPartnerListConfig, Partners } from '#site/types';
2+
import { shuffle } from '#site/util/array';
293

304
async function randomPartnerList(
315
partners: Array<Partners>,

apps/site/util/array.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import type { Partners } from '#site/types';
2+
3+
// Fisher-Yates shuffle algorithm with a seed for deterministic results
4+
export const shuffle = async (
5+
array: Array<Partners>,
6+
seed: number
7+
): Promise<Array<Partners>> => {
8+
const shuffled = [...array];
9+
const encoder = new TextEncoder();
10+
const buffer = encoder.encode(String(seed));
11+
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
12+
const hash = new Uint8Array(hashBuffer);
13+
14+
for (let i = shuffled.length - 1; i > 0; i--) {
15+
// Use hash bytes to generate deterministic "random" index
16+
const hashIndex = (i + seed) % 32;
17+
// Normalize to 0-1
18+
const randomValue = hash[hashIndex] / 255;
19+
20+
const j = Math.floor(randomValue * (i + 1));
21+
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
22+
}
23+
24+
return shuffled;
25+
};

0 commit comments

Comments
 (0)