Last active
June 2, 2019 20:11
-
-
Save nmanumr/eaabd5b05c69640910eb46eaa4d25a88 to your computer and use it in GitHub Desktop.
Parse single quiz MCQ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class McqParser { | |
getQuestionNode(doc) { | |
return doc.querySelector('.question_box>h3>p'); | |
} | |
getOption(labelEl) { | |
return new McqChoice( | |
labelEl.innerHTML, | |
labelEl.title | |
); | |
} | |
getOptions(doc) { | |
var options = []; | |
var labels = doc.querySelectorAll('.question_box>label'); | |
labels.forEach((labelEl) => { | |
options.push(this.getOption(labelEl)); | |
}) | |
return options; | |
} | |
parse(doc) { | |
return new MCQ( | |
this.getQuestionNode(doc), | |
this.getOptions(doc) | |
) | |
} | |
} | |
class MCQ { | |
constructor(text, choices, ans) { | |
this.text = text; | |
this.choices = choices; | |
this.ans = ans; | |
} | |
static loadFromObj(obj) { | |
var text; | |
if(typeof obj.text == 'string'){ | |
text = document.createElement('p'); | |
text.innerText = text; | |
} | |
else | |
text = obj.text; | |
return new MCQ(text, obj.choices, obj.ans); | |
} | |
getJSON() { | |
var options = this.choices.map((opt) => opt.getJSON()) | |
return { | |
text: this.text.innerText.trim(), | |
choices: options, | |
ans: this.ans | |
} | |
} | |
existsIn(qDict) { | |
for (var qId in qDict) { | |
if (qDict[qId].text == this.text.innerText.trim()) | |
return MCQ.loadFromObj(qDict[qId]); | |
} | |
} | |
mark(id) { | |
document.querySelector(`[value='${id}']`).click(); | |
} | |
getHash() { | |
return this.text.innerText.trim().hashCode(); | |
} | |
setAns(id) { | |
this.ans = id; | |
} | |
updateAnsFromText(text){ | |
for(var choice of this.choices){ | |
if(choice.text == text){ | |
this.ans = choice.id; | |
return; | |
} | |
} | |
} | |
} | |
class McqChoice { | |
constructor(text, id) { | |
this.text = text; | |
this.id = id; | |
} | |
getJSON() { | |
return { | |
text: this.text.trim(), | |
id: this.id | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment