Skip to content

Commit

Permalink
refactor: Shuffle showcase books on login page
Browse files Browse the repository at this point in the history
This commit refactors the ShowcaseBooks component on the login page to shuffle the order of the books displayed. Instead of using the original order from the API response, the books are now randomly shuffled using the Fisher-Yates algorithm. This provides a more dynamic and engaging experience for users.

The code changes include:
- Updating the v-for loop in the template to use the shuffledShowcase array instead of the original showcase.getShowcase array.
- Adding a new ref variable, shuffledShowcase, to store the shuffled array of books.
- Implementing the shuffleArray function to shuffle the array using the Fisher-Yates algorithm.
- Adding the secureRandom function to generate secure random numbers for shuffling.

These changes improve the user experience by presenting a different order of books each time the login page is loaded, making it more visually appealing and interesting.
  • Loading branch information
arnonrdp committed Jun 14, 2024
1 parent 0d4894b commit f32007e
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/components/login/ShowcaseBooks.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<template>
<section class="flex justify-around">
<figure v-for="book of showcase.getShowcase" :key="book.id">
<figure v-for="book of shuffledShowcase" :key="book.id">
<div class="cursor-pointer" @click="goTo(book.link)">
<img v-if="book.thumbnail" :src="book.thumbnail" :alt="$t('book.cover-image-alt', [book.title])" />
<img v-else src="@/assets/no_cover.jpg" :alt="$t('book.cover-image-alt', [book.title])" />
Expand All @@ -12,15 +12,31 @@
<script setup lang="ts">
import type { Book } from '@/models'
import { useShowcaseStore } from '@/store/showcase'
import { onMounted } from 'vue'
import { onMounted, ref } from 'vue'
const showcase = useShowcaseStore()
const shuffledShowcase = ref<Book[]>([])
onMounted(async () => {
await showcase.fetchShowcase()
showcase.getShowcase.sort(() => Math.random() - 0.5)
shuffledShowcase.value = shuffleArray(showcase.getShowcase)
})
function shuffleArray(array: Book[]): Book[] {
const result = array.slice()
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(secureRandom() * (i + 1))
;[result[i], result[j]] = [result[j], result[i]]
}
return result
}
function secureRandom(): number {
const buffer = new Uint8Array(1)
window.crypto.getRandomValues(buffer)
return buffer[0] / 255
}
function goTo(link: Book['link']) {
window.open(link, '_blank')
}
Expand Down

0 comments on commit f32007e

Please sign in to comment.