Improve ad shuffling

This commit is contained in:
Robbie Antenesse 2019-06-07 23:12:47 -06:00 committed by Robbie Antenesse
parent 352e6d3fc0
commit ca7d219a96
2 changed files with 12 additions and 3 deletions

View File

@ -69,6 +69,15 @@ export function removeTags(html) {
return html;
}
export function shuffle(array) {
// Fisher-Yates shuffle
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;
}
export function slugify(string) {
return removeDiacritics(string).replace(/[^a-zA-Z0-9-_]/g, '-');
}

View File

@ -1,10 +1,10 @@
import { DISPLAY_AD_EVERY } from '../constants.js';
import ads from '../../ads.json';
import { shuffle } from '../helpers.js';
export function setupAds() {
const shuffle = (a, b) => Math.random() > 0.5 ? 1 : -1;
const priority = ads.filter(ad => isActive(ad) && ad.isPriority).sort(shuffle);
const regular = ads.filter(ad => isActive(ad) && !ad.isPriority).sort(shuffle);
const priority = shuffle(ads.filter(ad => isActive(ad) && ad.isPriority));
const regular = shuffle(ads.filter(ad => isActive(ad) && !ad.isPriority));
window.ads = [...priority, ...regular];
}