User:TheGhostOfInky/js-quiz.js

var answerIcons = [ "Yes.png", "Kinda Yes.png", "Meh.png", "Kinda No.png", "No.png" ];

var answerNames = [ "Strongly Agree", "Agree", "Neutral", "Disagree", "Strongly Disagree" ];

/** * @typedef QuizParams */

/** * @param {QuizParams} params */ var Quiz = function (params) { this.number = 0; this.questions = params.questions; this.tiers = params.tiers; /**@type {number[]} */ this.scores = [];

/**    * @returns {string} */   this.currentQuestion = function  { return this.questions[this.number].title; }

/**    * @returns {number} */   this.currentNumber = function  { return this.number + 1; }

/**    * @param {number} score * @returns {string|null} */   this.nextQuestion = function (score) { console.log(score) this.scores[this.number] = score; if (this.number < (this.questions.length - 1)) { return this.questions[++this.number].title; } else { return null; }   }

/**    * @returns {string|null} */   this.previousQuestion = function  { if (this.number > 0) { return this.questions[--this.number].title; } else { return null }   }

/**    * @returns {[total: number, tier: string|null]} */   this.calculateScores = function  { var total = 0; for (var i = 0; i < this.questions.length; i++) { total += (this.scores[i] * this.questions[i].effect) / 5; }

var max = this.questions.reduce(function (acc, value) {           return acc + value.effect;        }, 0);

total /= max; total *= 100;

var tier = null; for (var j = 0; j < this.tiers.length; j++) { if (total >= this.tiers[j].lb && total <= this.tiers[j].ub) { tier = this.tiers[j].name; }       }

return [total, tier]; }

} /** * * @param {number} index * @param {Quiz} quiz * @param {HTMLDivElement} question * @param {JQuery} elm */ function createButton(index, quiz, question, elm) { var button = document.createElement("button");

var buttonHTML = ' ' + answerNames[index] + ' ';

button.innerHTML = buttonHTML; var weight = 5 - index;

button.onclick = function { var answer = quiz.nextQuestion(weight); if (answer) { question.textContent = answer; } else { var scores = quiz.calculateScores; var scoresDiv = ' You got ' + scores[0].toFixed(1) scoresDiv += "%, aka: " + scores[1] + ' '; elm.html(scoresDiv); }   }    return button; }

$(".js-quiz").each(function {    var elm = $(this);    var txt = elm.text;    var data = JSON.parse(atob(txt));    elm.html("");    var quiz = new Quiz(data);    var question = document.createElement("div");    question.textContent = quiz.currentQuestion;    elm.append(question);

for (var i = 0; i < 5; i++) { var button = createButton(i, quiz, question, elm); elm.append(button); }

var backButton = document.createElement("button"); backButton.classList.add("js-quiz-back-button"); backButton.textContent = "back";

backButton.onclick = function { var answer = quiz.previousQuestion; if (answer) { question.textContent = answer; }   }

elm.append(backButton); });