word/quiz: rewrite javascript object to class
authorMischa POSLAWSKY <perl@shiar.org>
Wed, 20 Oct 2021 21:35:08 +0000 (23:35 +0200)
committerMischa POSLAWSKY <perl@shiar.org>
Tue, 9 Nov 2021 03:14:15 +0000 (04:14 +0100)
word/quiz.js

index 3bfa2ca3097a42169631240fd17a4ecb4722a998..ef5e0d84735c1f41565916d10db7080306a878ca 100644 (file)
@@ -1,36 +1,35 @@
-let quiz = {
-dataurl: '/data/wordlist.nl.json',
+class Quiz {
+       next() {
+               let word = this.words.shift();
+               let form = put(this.form,
+                       '+img[src=$]+ul', `/data/word/en/${word[0]}.jpg`,
+               );
 
-next: () => {
-       let word = quiz.words.shift();
-       let form = put(quiz.form,
-               'img[src=$]+ul', `/data/word/en/${word[0]}.jpg`,
-       );
-
-       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);
-               }});
-       });
-},
-
-setup: () => {
-       fetch(quiz.dataurl).then(res => res.json()).then(json => {
-               quiz.form = document.getElementById('quiz');
-               quiz.words = Object.values(json)
+               let answers = [word[2], this.words[1][2], this.words[2][2], this.words[3][2]]
                        .sort(() => {return .5 - Math.random()}) // shuffle
-                       .map(row => row.split(/:/))
-               quiz.next();
-       });
-},
+               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);
+                       }});
+               });
+       }
+
+       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();
+               });
+       }
 };
 
-quiz.setup();
+new Quiz();