Skip to content

Commit

Permalink
randomize
Browse files Browse the repository at this point in the history
  • Loading branch information
greggman committed Apr 29, 2024
1 parent 528bb3e commit c572358
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 8 deletions.
9 changes: 9 additions & 0 deletions src/js/browser.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import {createElem as el} from './elem.js';
import { PseudoRandom } from './random.js';

const r = new PseudoRandom();
const tocElem = document.querySelector('#toc');
const toc = await (await fetch('toc.json')).json();

const seed = parseInt(sessionStorage.getItem('seed') || (Math.random() * 0x7FFF_FFFF));
sessionStorage.setItem('seed', seed);
r.reset(seed);

toc.forEach(v => v.rank = r.rand());
toc.sort((a, b) => a.rank - b.rank);

for (const {id, name, username, avatarUrl, screenshotURL} of toc) {
const artUrl = `art/${id}`;
tocElem.appendChild(el('div', [
Expand Down
16 changes: 8 additions & 8 deletions src/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -980,14 +980,6 @@ define([
};
}

document.querySelectorAll('.parentLink').forEach(elem => {
elem.addEventListener('click', function(event) {
if (parent) {
parent.location.href = this.href;
}
});
});

var notifier = new Notifier({
timeout: 7.5,
container: document.body,
Expand Down Expand Up @@ -2145,6 +2137,14 @@ define([
}
}

document.querySelectorAll('.parentLink').forEach(elem => {
elem.addEventListener('click', function(event) {
if (parent) {
parent.location.href = this.href;
}
});
});

vs.setSettings(settings, options);
}

Expand Down
47 changes: 47 additions & 0 deletions src/js/random.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const RANDOM_RANGE = Math.pow(2, 32);

export class PseudoRandom {
#randomSeed = 0;

/**
* Returns a deterministic pseudo random number between 0 and 1
* @return {number} a random number between 0 and 1
*/
random() {
return (this.#randomSeed =
(134775813 * this.#randomSeed + 1) %
RANDOM_RANGE) / RANDOM_RANGE;
};

/**
* Reset the pseudo random number generator (whit optional seed)
* @param {number} [seed]
*/
reset(seed = 0) {
this.#randomSeed = seed;
}

/**
* Return a random number between 0 and n (but not n)
* @param {number} [min]
* @param {number} [max]
*/
rand(min, max) {
if (min === undefined) {
min = 0;
max = 1;
} else if (max === undefined) {
max = min;
min = 0;
}
return min + this.random() * (max - min);
}

/**
* Return a random integer between 0 and n-1
* @param {number} n
*/
randInt(min, max) {
return Math.floor(this.rand(min, max));
}
}

0 comments on commit c572358

Please sign in to comment.