Skip to content

Commit eb7ab94

Browse files
Move randomization from backend to client-side
- Remove order_by('?') from backend to avoid database overhead - Implement Fisher-Yates shuffle in QuestionCarousel component - Provides true per-visit randomization instead of per-cache-refresh - Keeps backend query deterministic and cache-friendly Co-authored-by: Hlib <[email protected]>
1 parent aacea77 commit eb7ab94

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

front_end/src/app/(main)/(home)/components/questions_carousel.tsx

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { faArrowRight } from "@fortawesome/free-solid-svg-icons";
44
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
55
import Link from "next/link";
66
import { useTranslations } from "next-intl";
7-
import React, { FC } from "react";
7+
import React, { FC, useMemo } from "react";
88

99
import Carousel, { CarouselItem } from "@/components/carousel";
1010
import ForecastCard from "@/components/forecast_card";
@@ -19,6 +19,16 @@ type Props = {
1919
const QuestionCarousel: FC<Props> = ({ posts }) => {
2020
const t = useTranslations();
2121

22+
// Randomize posts on each render using Fisher-Yates shuffle
23+
const shuffledPosts = useMemo(() => {
24+
const array = [...posts];
25+
for (let i = array.length - 1; i > 0; i--) {
26+
const j = Math.floor(Math.random() * (i + 1));
27+
[array[i], array[j]] = [array[j], array[i]];
28+
}
29+
return array;
30+
}, [posts]);
31+
2232
return (
2333
<Carousel
2434
className="flex flex-col gap-4 md:gap-12"
@@ -34,7 +44,7 @@ const QuestionCarousel: FC<Props> = ({ posts }) => {
3444
</div>
3545
}
3646
>
37-
{posts.map((p) => (
47+
{shuffledPosts.map((p) => (
3848
<CarouselItem key={p.id}>
3949
<ForecastCard
4050
post={p}

posts/views.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -123,9 +123,6 @@ def posts_list_homeage_api_view(request):
123123

124124
qs = get_posts_feed(Post.objects.all(), show_on_homepage=True)
125125

126-
# Randomize the order of posts
127-
qs = qs.order_by('?')
128-
129126
return Response(
130127
serialize_post_many(qs, with_cp=True, include_cp_history=True, group_cutoff=3)
131128
)

0 commit comments

Comments
 (0)