From 425ec7c5e92313ddf6855ba47f4c1b6d094c056f Mon Sep 17 00:00:00 2001 From: Benny Guo Date: Mon, 21 Aug 2023 11:45:33 +0800 Subject: [PATCH] fix: footer link random pick friend infinite loop --- src/components/Footer/FooterLink.vue | 35 +++++++++++++++++++++++----- src/utils/index.ts | 8 +++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/components/Footer/FooterLink.vue b/src/components/Footer/FooterLink.vue index 12a50dc7..aea6ad84 100644 --- a/src/components/Footer/FooterLink.vue +++ b/src/components/Footer/FooterLink.vue @@ -50,6 +50,12 @@ import { useAppStore } from '@/stores/app' import { useArticleStore } from '@/stores/article' import { PropType, computed, defineComponent, onMounted, ref, watch } from 'vue' import SvgIcon from '@/components/SvgIcon/index.vue' +import { shuffleArray } from '@/utils' + +enum FriendLinkRandomMode { + 'RANDOM' = 'random', + 'SHUFFLE' = 'SHUFFLE' +} export default defineComponent({ name: 'ARFooterLink', @@ -63,21 +69,38 @@ export default defineComponent({ const loadingLinks = ref(true) const linksData = ref([]) const bloggers = ref([]) + const maxShuffleLimit = 100 const refreshLinkData = () => { loadingLinks.value = true linksData.value = [] + let uniqueBloggers = [ + ...new Map(bloggers.value.flat().map(m => [m.nick, m])).values() + ] setTimeout(() => { const recordSet = new Set() - let friendsCount = bloggers.value.length < 5 ? bloggers.value.length : 5 + let friendsCount = uniqueBloggers.length < 5 ? uniqueBloggers.length : 5 + let mode: FriendLinkRandomMode = FriendLinkRandomMode.SHUFFLE + if (uniqueBloggers.length > maxShuffleLimit) { + mode = FriendLinkRandomMode.RANDOM + } + + if (mode === FriendLinkRandomMode.SHUFFLE) { + uniqueBloggers = shuffleArray(uniqueBloggers) + } while (friendsCount > 0) { - const pair = bloggers.value[Math.floor(Math.random() * 24)] - const blogger = pair[Math.floor(Math.random() * 2)] - if (!recordSet.has(blogger.nick)) { - recordSet.add(blogger.nick) - linksData.value.push(blogger) + if (mode === FriendLinkRandomMode.SHUFFLE) { + linksData.value.push(uniqueBloggers[friendsCount - 1]) friendsCount-- + } else { + const blogger = + uniqueBloggers[Math.floor(Math.random() * friendsCount)] + if (!recordSet.has(blogger.nick)) { + recordSet.add(blogger.nick) + linksData.value.push(blogger) + friendsCount-- + } } } loadingLinks.value = false diff --git a/src/utils/index.ts b/src/utils/index.ts index 35a15840..da5851a0 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -156,3 +156,11 @@ export function cleanPath(path: string) { return path } + +export function shuffleArray(array: T[]): T[] { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)) + ;[array[i], array[j]] = [array[j], array[i]] + } + return array +}