X-Git-Url: http://git.shiar.nl/sheet.git/blobdiff_plain/557e9a9b737294f5e170f8f5474ff750ab72cb4a..1d174caf0e66efe73a17b6fefb11abe8df2b0750:/word/quiz.js diff --git a/word/quiz.js b/word/quiz.js index 70f8500..187aea7 100644 --- a/word/quiz.js +++ b/word/quiz.js @@ -1,14 +1,57 @@ Array.prototype.shuffle = function () { - return this.sort(() => {return .5 - Math.random()}); + for (let i = this.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); // random index 0..i + [this[i], this[j]] = [this[j], this[i]]; // swap elements + } + return this; }; class WordQuiz { dataselect(json) { + // find viable rows from json data let rows = Object.values(json); + if (this.preset.cat !== undefined) { + let cats = {}; // category lookup + for (let i in json) { + let cat = json[i][3]; + if (!cats[cat]) cats[cat] = []; + cats[cat].push(i) + } + + rows = []; + let children = cats[this.preset.cat]; + for (let loop = 0; children.length && loop < 20; loop++) { + rows.push(...children); + children = children.map(cat => cats[cat]).filter(is => is).flat(); + } + rows = rows.map(row => json[row]).filter(row => row[2]); + } + if (this.preset.level !== undefined) { + rows = rows.filter(row => row[1] <= this.preset.level); + } + + { + let cats = new Set(); + let subcats = rows.map(row => row[3]); // direct parents + for (let loop = 0; subcats.length && loop < 20; loop++) { + subcats.forEach(cat => cats.add(cat)); + subcats = subcats.map(row => json[row] && json[row][3]).filter(val => val); // recurse grandparents + } + rows = rows.filter(row => !cats.has(row[2])); // remove referenced categories + } return rows.shuffle(); } load(dataurl) { + this.preset = {}; + let input; + if (input = window.location.hash.match(/\d+/)) { + this.preset.cat = input[0]; + } + if (window.location.hash.match(/a/)) { + this.preset.level = 2; + } + fetch(dataurl).then(res => res.json()).then(json => { this.words = this.dataselect(json) this.setup();