Last active
September 14, 2022 22:55
-
-
Save gheja/262ca781e5de2028c0f2129182e222eb to your computer and use it in GitHub Desktop.
Shuffle button for js13kGames voting page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Shuffle button for js13kGames voting page | |
// @namespace https://github.com/gheja/ | |
// @version 0.1 | |
// @description try to take over the world! | |
// @author gheja, nes | |
// @match https://dev.js13kgames.com/games | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=js13kgames.com | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
// based on code by @nes, thanks! | |
// NOTE: switching categories break the order | |
let sort_storage_key = "sort_seed"; | |
function sortRun(n) { | |
if (n === undefined) | |
{ | |
n = localStorage.getItem(sort_storage_key); | |
} | |
if (n === null) { | |
// do not shuffle initially | |
return; | |
} | |
let rnd = parseInt(n); | |
function randPrngSeed() { | |
let mod = 2 ** 31 - 1; | |
rnd = 16807 * rnd % mod; | |
return (rnd - 1) / (mod - 1); | |
} | |
function arrRandSort(arr) { | |
for (let i = arr.length - 1; i > 0; i--) { | |
let j = Math.floor(randPrngSeed() * (i + 1)); | |
let tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
} | |
} | |
function arrSortByLink(arr) { | |
arr.sort((a, b) => { | |
return a.href.localeCompare(b.href); | |
}); | |
} | |
var games = document.getElementById("g-games"); | |
var gamesChildren = Array.from(document.getElementById("g-games").childNodes); | |
arrSortByLink(gamesChildren); | |
arrRandSort(gamesChildren); | |
while (games.firstChild) { | |
games.removeChild(games.firstChild); | |
} | |
games.append(...gamesChildren); | |
} | |
function sortShuffle() { | |
let n = Math.floor(Math.random() * 10000); | |
localStorage.setItem(sort_storage_key, n); | |
// localstorage does not update immediately | |
sortRun(n); | |
} | |
function attemptToSort() { | |
if (document.getElementById("g-games").childNodes.length == 0) { | |
window.setTimeout(attemptToSort.bind(), 50); | |
return; | |
} | |
sortRun(); | |
} | |
function sortInit() { | |
let tmp = document.createElement("div"); | |
tmp.className = "btn"; | |
tmp.addEventListener("click", sortShuffle.bind()); | |
tmp.innerHTML = "Shuffle"; | |
document.getElementById("g-categories").appendChild(tmp); | |
// the entries are not yet loaded when "load" fires | |
attemptToSort(); | |
} | |
window.addEventListener('load', sortInit); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment