word/quiz: preset configuration filters level
[sheet.git] / word / quiz.js
index 3bfa2ca3097a42169631240fd17a4ecb4722a998..146aff73e61171c10f81779aad8be30777d7da35 100644 (file)
@@ -1,36 +1,30 @@
-let quiz = {
-dataurl: '/data/wordlist.nl.json',
-
-next: () => {
-       let word = quiz.words.shift();
-       let form = put(quiz.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], quiz.words[1][2], quiz.words[2][2], quiz.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(quiz.next, 500);
-               }});
-       });
-},
+class WordQuiz {
+       dataselect(json) {
+               // find viable rows from json data
+               let rows = Object.values(json);
+               if (this.preset.level !== undefined) {
+                       rows = rows.filter(row => row[1] <= this.preset.level);
+               }
+               return rows.shuffle();
+       }
 
-setup: () => {
-       fetch(quiz.dataurl).then(res => res.json()).then(json => {
-               quiz.form = document.getElementById('quiz');
-               quiz.words = Object.values(json)
-                       .sort(() => {return .5 - Math.random()}) // shuffle
-                       .map(row => row.split(/:/))
-               quiz.next();
-       });
-},
-};
+       load(dataurl) {
+               this.preset = {};
+               fetch(dataurl).then(res => res.json()).then(json => {
+                       this.words = this.dataselect(json)
+                       this.setup();
+               });
+       }
 
-quiz.setup();
+       constructor(dataurl) {
+               this.load(dataurl);
+       }
+}