Skip to content

Commit 96e8e2a

Browse files
authored
Merge pull request #55 from LilianBoulard/fix-rng
Fix RNG
2 parents ad41e20 + ae9cca9 commit 96e8e2a

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

server/controllers/posts.ts

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,26 @@ export async function random(query: string | null = null): Promise<PostSummary |
111111
id = post?.id || null;
112112
} else {
113113
const key = getCacheKey(query);
114-
const cachePage = await getCachedPosts(key);
115-
116-
id = cachePage.posts[Math.floor(Math.random() * cachePage.posts.length)] || null;
114+
115+
key.offset = 0;
116+
const firstPage = await getCachedPosts(key);
117+
const total = firstPage.total;
118+
119+
if(total === 0) {
120+
id = null;
121+
} else {
122+
// Pick a random position across the entire result set
123+
const randomPosition = Math.floor(Math.random() * total);
124+
125+
// Calculate which cache page contains this position
126+
const cacheStart = Math.floor(randomPosition / CACHE_SIZE) * CACHE_SIZE;
127+
key.offset = cacheStart;
128+
const cachePage = await getCachedPosts(key);
129+
130+
// Get the post at the random position within this page
131+
const indexInPage = randomPosition - cacheStart;
132+
id = cachePage.posts[indexInPage] || null;
133+
}
117134
}
118135

119136
const post: PostSummary | null = await db.queryFirst(SQL`

0 commit comments

Comments
 (0)