Skip to content

Commit 19efadf

Browse files
committed
refactor: web crypto api
1 parent 0cac120 commit 19efadf

2 files changed

Lines changed: 15 additions & 9 deletions

File tree

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
1-
import { createHash } from 'node:crypto';
2-
31
import type {
42
RandomPartnerListConfig,
53
Partners,
64
} from '#site/types/partners.js';
75

86
// Fisher-Yates shuffle algorithm with a seed for deterministic results
9-
function shuffle(array: Array<Partners>, seed: number): Array<Partners> {
7+
async function shuffle(
8+
array: Array<Partners>,
9+
seed: number
10+
): Promise<Array<Partners>> {
1011
const shuffled = [...array];
11-
const hash = createHash('sha256').update(String(seed)).digest();
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);
1216

1317
for (let i = shuffled.length - 1; i > 0; i--) {
1418
// Use hash bytes to generate deterministic "random" index
@@ -23,10 +27,10 @@ function shuffle(array: Array<Partners>, seed: number): Array<Partners> {
2327
return shuffled;
2428
}
2529

26-
function randomPartnerList(
30+
async function randomPartnerList(
2731
partners: Array<Partners>,
2832
config: RandomPartnerListConfig
29-
) {
33+
): Promise<Array<Partners>> {
3034
const { pick = 4, dateSeed = 5, category } = config;
3135

3236
// Generate a deterministic seed based on current time that changes every X minutes
@@ -37,7 +41,9 @@ function randomPartnerList(
3741
? partners.filter(p => p.categories.includes(category))
3842
: partners;
3943

40-
return shuffle(filtered, seed).slice(0, pick ?? filtered.length);
44+
const shuffled = await shuffle(filtered, seed);
45+
46+
return shuffled.slice(0, pick ?? filtered.length);
4147
}
4248

4349
export { randomPartnerList };

apps/site/hooks/react-client/usePartnersList.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ const usePartnersList = ({
3636
// Although whilst we are deployed on Vercel or other environment that supports ISR
3737
// (Incremental Static Generation) whose would invalidate the cache every 5 minutes
3838
// We want to ensure that this feature is compatible on a full-static environment
39-
const renderSponsorsAnimation = setTimeout(() => {
39+
const renderSponsorsAnimation = setTimeout(async () => {
4040
initialRenderer.current = false;
4141

4242
setSeedList(
43-
randomPartnerList(logos, {
43+
await randomPartnerList(logos, {
4444
pick: maxLength,
4545
dateSeed: 1,
4646
category: categories,

0 commit comments

Comments
 (0)