Skip to content

Commit c8fb376

Browse files
committed
add randomizeArray
1 parent a7a1dab commit c8fb376

File tree

3 files changed

+14
-7
lines changed

3 files changed

+14
-7
lines changed

src/components/Gallery.astro

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { getImage } from 'astro:assets';
33
44
import ReactGallery from '@/components/react/Gallery';
55
import { IMAGE_SIZES } from '@/constants/image';
6+
import { randomizeArray } from '@/utils/objects';
67
import { cn } from '@/utils/styles';
78
89
import type { ImageProps } from '@/types/common';
@@ -72,11 +73,13 @@ const reactImages = await Promise.all(
7273
imagesMetadata.map((metadata) => imageMetadataToReactImageProps(metadata))
7374
);
7475
76+
const randomizedReactImages = randomizeArray(reactImages);
77+
7578
// console.log('reactImages', reactImages);
7679
7780
const { class: className } = Astro.props;
7881
---
7982

8083
<div class={cn('', className)}>
81-
<ReactGallery client:only="react" images={reactImages} />
84+
<ReactGallery client:only="react" images={randomizedReactImages} />
8285
</div>

src/modules/post/random.ts

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { CONFIG } from '@/config';
2+
import { randomizeArray } from '@/utils/objects';
23

34
import type { Post } from '@/types/post';
45

@@ -22,12 +23,9 @@ export const getRandomPosts = ({
2223

2324
if (!(filteredPosts.length > 0)) return [];
2425

25-
const shuffledPosts = filteredPosts
26-
.map((post) => ({ post, sort: Math.random() }))
27-
.sort((a, b) => a.sort - b.sort)
28-
.map(({ post }) => post);
26+
const randomizedPosts = randomizeArray(filteredPosts);
2927

30-
if (shuffledPosts.length < count) return shuffledPosts;
28+
if (randomizedPosts.length < count) return randomizedPosts;
3129

32-
return shuffledPosts.slice(0, count);
30+
return randomizedPosts.slice(0, count);
3331
};

src/utils/objects.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
11
// eslint-disable-next-line @typescript-eslint/no-explicit-any
22
export const filterUndefined = <T extends Record<string, any>>(obj: T): T =>
33
Object.fromEntries(Object.entries(obj).filter(([_key, value]) => value !== undefined)) as T;
4+
5+
export const randomizeArray = <T>(array: T[]): T[] =>
6+
array
7+
.map((item) => ({ item, sort: Math.random() }))
8+
.sort((a, b) => a.sort - b.sort)
9+
.map(({ item }) => item);

0 commit comments

Comments
 (0)