X-Git-Url: http://git.shiar.nl/sheet.git/blobdiff_plain/e889c7543227d2aeee90553fea9c59524c2cec95..f88a74c510e90c9c864d37bfaaf23fefa1a0fbdc:/word/quiz.js diff --git a/word/quiz.js b/word/quiz.js index ef5e0d8..e2e8cb6 100644 --- a/word/quiz.js +++ b/word/quiz.js @@ -1,35 +1,56 @@ -class Quiz { - next() { - let word = this.words.shift(); - let form = put(this.form, - '+img[src=$]+ul', `/data/word/en/${word[0]}.jpg`, - ); +Array.prototype.shuffle = function () { + 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; +}; - let answers = [word[2], this.words[1][2], this.words[2][2], this.words[3][2]] - .sort(() => {return .5 - Math.random()}) // shuffle - answers.forEach(suggest => { - let option = put(form, 'li', suggest, {onclick: () => { - if (suggest != word[2]) { - // incorrect - put(option, '.wrong'); - return; - } - put(option, '.good'); - window.setTimeout(() => this.next(), 500); - }}); - }); +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(); } - constructor() { - this.dataurl = '/data/wordlist.nl.json'; - fetch(this.dataurl).then(res => res.json()).then(json => { - this.form = document.getElementById('quiz'); - this.words = Object.values(json) - .sort(() => {return .5 - Math.random()}) // shuffle - .map(row => row.split(/:/)) - this.next(); + load(dataurl) { + this.preset = {}; + fetch(dataurl).then(res => res.json()).then(json => { + this.words = this.dataselect(json) + this.setup(); }); } -}; -new Quiz(); + constructor(dataurl) { + this.load(dataurl); + } +}