diff --git a/src/components/top-matter/OnThisDay.vue b/src/components/top-matter/OnThisDay.vue index 39b12022..9a1a7c42 100644 --- a/src/components/top-matter/OnThisDay.vue +++ b/src/components/top-matter/OnThisDay.vue @@ -115,10 +115,16 @@ export default class OnThisDay extends Mixins(GlobalMixin) { yearObj.photos.push(photo); } - // Randomly choose preview photo + // For each year, randomly choose 10 photos to display for (const year of this.years) { - const index = Math.floor(Math.random() * year.photos.length); - year.preview = year.photos[index]; + year.photos = utils.randomSubarray(year.photos, 10); + } + + // Choose preview photo + for (const year of this.years) { + // Try to prioritize landscape photos + const landscape = year.photos.filter(p => p.w > p.h); + year.preview = utils.randomChoice(landscape) || utils.randomChoice(year.photos); year.url = getPreviewUrl(year.preview.fileid, year.preview.etag, false, 512); } diff --git a/src/services/Utils.ts b/src/services/Utils.ts index c8335b13..c05fd0fd 100644 --- a/src/services/Utils.ts +++ b/src/services/Utils.ts @@ -123,6 +123,27 @@ export function roundHalf(num: number) { return Math.round(num * 2) / 2; } +/** Choose a random element from an array */ +export function randomChoice(arr: any[]) { + return arr[Math.floor(Math.random() * arr.length)]; +} + +/** + * Choose a random sub array from an array + * https://stackoverflow.com/a/11935263/4745239 + */ +export function randomSubarray(arr: any[], size: number) { + if (arr.length <= size) return arr; + var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index; + while (i-- > min) { + index = Math.floor((i + 1) * Math.random()); + temp = shuffled[index]; + shuffled[index] = shuffled[i]; + shuffled[i] = temp; + } + return shuffled.slice(min); +} + /** * Convert server-side flags to bitmask * @param photo Photo to process