From 0fce475a95750e00e539737c3000ad7c0249ad4a Mon Sep 17 00:00:00 2001 From: valadaptive Date: Sat, 9 Dec 2023 22:37:49 -0500 Subject: [PATCH] Implement random sort with a shuffle Sorting with a random comparator doesn't actually shuffle an array. Depending on the sorting algorithm used, there will be a bias to the shuffle (see https://bost.ocks.org/mike/shuffle/compare.html). If you open that link in Firefox, the bias will be especially bad. Instead of implementing "random" character sort using a random sort comparator, use the shuffle function instead. --- public/scripts/power-user.js | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/public/scripts/power-user.js b/public/scripts/power-user.js index 21806cb99..75f22581d 100644 --- a/public/scripts/power-user.js +++ b/public/scripts/power-user.js @@ -35,7 +35,7 @@ import { registerSlashCommand } from './slash-commands.js'; import { tags } from './tags.js'; import { tokenizers } from './tokenizers.js'; -import { countOccurrences, debounce, delay, isOdd, resetScrollHeight, sortMoments, stringToRange, timestampToMoment } from './utils.js'; +import { countOccurrences, debounce, delay, isOdd, resetScrollHeight, shuffle, sortMoments, stringToRange, timestampToMoment } from './utils.js'; export { loadPowerUserSettings, @@ -1818,10 +1818,6 @@ export function renderStoryString(params) { const sortFunc = (a, b) => power_user.sort_order == 'asc' ? compareFunc(a, b) : compareFunc(b, a); const compareFunc = (first, second) => { - if (power_user.sort_order == 'random') { - return Math.random() > 0.5 ? 1 : -1; - } - const a = first[power_user.sort_field]; const b = second[power_user.sort_field]; @@ -1853,6 +1849,11 @@ function sortEntitiesList(entities) { return; } + if (power_user.sort_order === 'random') { + shuffle(entities); + return; + } + entities.sort((a, b) => { if (a.type === 'tag' && b.type !== 'tag') { return -1;