quizz
Version:
A Simple Quizz
47 lines (46 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var diacritics = require("diacritics");
var levenshtein = require("js-levenshtein");
var LETTER_REGEXP = /\w/g;
var HIDE_PERCENT = 2 / 3;
var Question = /** @class */ (function () {
function Question(question, answer) {
this.question = question;
this.answer = answer;
this._answer = this.prepareAnswer(this.answer);
this._maxLevenshtein = Math.floor(this._answer.length / 5);
}
Question.prototype.prepareAnswer = function (answer) {
return diacritics.remove(answer)
.toLowerCase()
.trim()
.replace(/\W/g, ' ');
};
Question.prototype.check = function (answer) {
var preparedAnswer = this.prepareAnswer(answer);
return levenshtein(preparedAnswer, this._answer) <= this._maxLevenshtein;
};
Question.prototype.hint = function (level, placeholder) {
if (level === void 0) { level = 1; }
if (placeholder === void 0) { placeholder = '□'; }
switch (level) {
case 1:
return this._answer.replace(LETTER_REGEXP, placeholder);
case 2:
var answer = this._answer;
var answerLength = (answer.match(LETTER_REGEXP) || []).length;
var numberOfLettersToHide = Math.floor(answerLength * HIDE_PERCENT);
while (numberOfLettersToHide) {
var randomIndex = Math.floor(Math.random() * answer.length);
if (LETTER_REGEXP.test(answer[randomIndex])) {
answer = answer.substr(0, randomIndex) + placeholder + answer.substr(randomIndex + 1);
numberOfLettersToHide -= 1;
}
}
return answer;
}
};
return Question;
}());
exports.Question = Question;