Skip to content

Commit

Permalink
add randomizeArray
Browse files Browse the repository at this point in the history
  • Loading branch information
nemanjam committed Aug 17, 2024
1 parent a7a1dab commit c8fb376
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 7 deletions.
5 changes: 4 additions & 1 deletion src/components/Gallery.astro
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getImage } from 'astro:assets';
import ReactGallery from '@/components/react/Gallery';
import { IMAGE_SIZES } from '@/constants/image';
import { randomizeArray } from '@/utils/objects';
import { cn } from '@/utils/styles';
import type { ImageProps } from '@/types/common';
Expand Down Expand Up @@ -72,11 +73,13 @@ const reactImages = await Promise.all(
imagesMetadata.map((metadata) => imageMetadataToReactImageProps(metadata))
);
const randomizedReactImages = randomizeArray(reactImages);
// console.log('reactImages', reactImages);
const { class: className } = Astro.props;
---

<div class={cn('', className)}>
<ReactGallery client:only="react" images={reactImages} />
<ReactGallery client:only="react" images={randomizedReactImages} />
</div>
10 changes: 4 additions & 6 deletions src/modules/post/random.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CONFIG } from '@/config';
import { randomizeArray } from '@/utils/objects';

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

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

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

const shuffledPosts = filteredPosts
.map((post) => ({ post, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ post }) => post);
const randomizedPosts = randomizeArray(filteredPosts);

if (shuffledPosts.length < count) return shuffledPosts;
if (randomizedPosts.length < count) return randomizedPosts;

return shuffledPosts.slice(0, count);
return randomizedPosts.slice(0, count);
};
6 changes: 6 additions & 0 deletions src/utils/objects.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const filterUndefined = <T extends Record<string, any>>(obj: T): T =>
Object.fromEntries(Object.entries(obj).filter(([_key, value]) => value !== undefined)) as T;

export const randomizeArray = <T>(array: T[]): T[] =>
array
.map((item) => ({ item, sort: Math.random() }))
.sort((a, b) => a.sort - b.sort)
.map(({ item }) => item);

0 comments on commit c8fb376

Please sign in to comment.