thisday: improve sampling

old-stable24
Varun Patil 2022-10-18 10:52:44 -07:00
parent c546c107af
commit 1baf07e65a
2 changed files with 30 additions and 3 deletions

View File

@ -115,10 +115,16 @@ export default class OnThisDay extends Mixins(GlobalMixin) {
yearObj.photos.push(photo); yearObj.photos.push(photo);
} }
// Randomly choose preview photo // For each year, randomly choose 10 photos to display
for (const year of this.years) { for (const year of this.years) {
const index = Math.floor(Math.random() * year.photos.length); year.photos = utils.randomSubarray(year.photos, 10);
year.preview = year.photos[index]; }
// 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); year.url = getPreviewUrl(year.preview.fileid, year.preview.etag, false, 512);
} }

View File

@ -123,6 +123,27 @@ export function roundHalf(num: number) {
return Math.round(num * 2) / 2; 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 * Convert server-side flags to bitmask
* @param photo Photo to process * @param photo Photo to process