-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquiz.js
223 lines (191 loc) · 8.75 KB
/
quiz.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
let currentSubject;
let questions = [];
let currentQuestionIndex = 0;
let correctAnswers = 0;
const subjects = ["abstract_algebra.csv", "anatomy.csv", "astronomy.csv", "business_ethics.csv", "clinical_knowledge.csv", "college_biology.csv", "college_chemistry.csv", "college_computer_science.csv", "college_mathematics.csv", "college_medicine.csv", "college_physics.csv", "computer_security.csv", "conceptual_physics.csv", "econometrics.csv", "electrical_engineering.csv", "elementary_mathematics.csv", "formal_logic.csv", "global_facts.csv", "high_school_biology.csv", "high_school_chemistry.csv", "high_school_computer_science.csv", "high_school_european_history.csv", "high_school_geography.csv", "high_school_government_and_politics.csv", "high_school_macroeconomics.csv", "high_school_mathematics.csv", "high_school_microeconomics.csv", "high_school_physics.csv", "high_school_psychology.csv", "high_school_statistics.csv", "high_school_us_history.csv", "high_school_world_history.csv", "human_aging.csv", "human_sexuality.csv", "international_law.csv", "jurisprudence.csv", "logical_fallacies.csv", "machine_learning.csv", "management.csv", "marketing.csv", "medical_genetics.csv", "miscellaneous.csv", "moral_disputes.csv", "moral_scenarios.csv", "nutrition.csv", "philosophy.csv", "prehistory.csv", "professional_accounting.csv", "professional_law.csv", "professional_medicine.csv", "professional_psychology.csv", "public_relations.csv", "security_studies.csv", "sociology.csv", "us_foreign_policy.csv", "virology.csv", "world_religions.csv"];
//https://stackoverflow.com/a/2450976
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex > 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
function loadSubjects() {
// Example subjects - replace with actual file names
const select = document.getElementById('subjectSelect');
subjects.forEach(subject => {
let option = document.createElement('option');
option.value = subject;
option.textContent = subject.split('.')[0];
select.appendChild(option);
});
}
function fetchCsv(url) {
return fetch(url).then(response => response.text());
}
function parseCsv(csv) {
const lines = csv.split('\n');
return lines.map(line => parseCsvLine(line)).filter(line => line !== null);
}
function parseCsvLine(line) {
let result = [];
let current = '';
let inQuotes = false;
for (let i = 0; i < line.length; i++) {
const char = line[i];
if (char === '"' && (i === 0 || i+1 === line.length || line[i - 1] === ',' || line[i + 1] === ',')) {
// Toggle the inQuotes flag if we're at the start of a new quoted field
inQuotes = !inQuotes;
} else if (char === ',' && !inQuotes) {
// If we hit a comma and we're not within quotes, push the field to the result
result.push(current.trim());
current = '';
}
else {
current += char;
}
}
// Push the last field, as it's not followed by a comma
result.push(current.trim());
// Assuming the format: question, option A, option B, option C, option D, answer
if (result.length === 6 && (result[5] === "A" || result[5] === "B" || result[5] === "C" || result[5] === "D")) {
const [question, optA, optB, optC, optD, answer] = result;
return { question, options: [optA, optB, optC, optD], answer };
} else {
// Handle error or return a default value
console.error('Invalid CSV format');
console.error(line);
return null;
}
}
function loadQuestions(subject, option) {
if (subject !== null) {
const url = `./${subject}`; // Path to the CSV file
fetchCsv(url)
.then(parseCsv)
.then(loadedQuestions => {
questions = shuffle(loadedQuestions);
displayQuestion();
});
} else {
const csvs = option === 1 ? subjects
: option === 2 ?
subjects.filter(subject => !subject.includes("elementary") && !subject.includes("high_school"))
: subjects.filter(subject => !subject.includes("elementary") && !subject.includes("high_school") && !subject.includes("college"));
let promises = csvs.map(csv => fetchCsv(csv)
.then(parseCsv));
Promise.all(promises).then((values) => {
questions = shuffle(values.flat());
}).then (() => {
displayQuestion()});
}
}
function startQuiz(option) {
if (option === 0) {
currentSubject = document.getElementById('subjectSelect').value;
loadQuestions(currentSubject);
} else if (option === 1) {
loadQuestions(null, 1);
}
else if (option === 2) {
loadQuestions(null, 2);
}else if (option === 3) {
loadQuestions(null, 3);
}
document.getElementById('quizContainer').style.display = 'block';
document.getElementById('startContainer').style.display = 'none';
}
function displayQuestion() {
let questionObj = questions[currentQuestionIndex];
let questionElement = document.getElementById('question');
let optionsElement = document.getElementById('options');
// Clear previous options
optionsElement.innerHTML = '';
// Set the question text
questionElement.innerText = questionObj.question;
// Create and display options
questionObj.options.forEach((option, index) => {
let optionButton = document.createElement('button');
optionButton.textContent = `${String.fromCharCode(65 + index)}. ${option}`;
optionButton.onclick = () => checkAnswer(String.fromCharCode(65 + index));
optionsElement.appendChild(optionButton);
});
// Update statistics
updateStats();
}
function updateStats() {
let totalQuestions = questions.length;
let answeredQuestions = currentQuestionIndex;
let correctPercentage = (correctAnswers / answeredQuestions) * 100;
let questionsRemaining = totalQuestions - answeredQuestions;
let statsElement = document.getElementById('stats');
statsElement.innerHTML = `
Questions Answered: ${answeredQuestions} / ${totalQuestions}<br>
Correct Answers: ${correctAnswers}<br>
Correctness: ${correctPercentage.toFixed(2)}%<br>
Questions Remaining: ${questionsRemaining}
`;
}
function checkAnswer(selectedOption) {
let correctOption = questions[currentQuestionIndex].answer;
if (selectedOption === correctOption) {
correctAnswers++;
}
displayCorrectAnswer(questions[currentQuestionIndex].question,
questions[currentQuestionIndex].options[correctOption.charCodeAt()-65],
selectedOption === correctOption,
questions[currentQuestionIndex].options[selectedOption.charCodeAt()-65]);
let copyData = document.getElementById('copyData');
copyData.innerHTML = `${questions[currentQuestionIndex].question} ${questions[currentQuestionIndex].options.map((value, index) => String.fromCharCode(65 + index) + ". " + value).join(" ")}`
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
displayQuestion();
} else {
endQuiz();
}
}
function displayCorrectAnswer(lastQuestion, correctOption, wasCorrect, yourSelection) {
let answerDisplay = document.getElementById('answerDisplay');
let lastQuestionDisplay = document.getElementById('lastQuestionDisplay');
lastQuestionDisplay.innerHTML = lastQuestion;
answerDisplay.innerHTML = `Were you correct?: ${wasCorrect}. <br/> Last Correct Answer: ${correctOption} <br/> You Selected: ${yourSelection} <br/>`;
answerDisplay.style.display = 'block';
lastQuestionDisplay.style.display = 'none';
}
function showLastQuestion() {
let lastQuestionDisplay = document.getElementById('lastQuestionDisplay');
lastQuestionDisplay.style.display = 'block';
}
function copyLastQuestion() {
navigator.clipboard.writeText(copyData.innerHTML);
}
function nextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
displayQuestion();
} else {
endQuiz();
}
}
function endQuiz() {
// Hide the question and options
document.getElementById('quizContainer').style.display = 'none';
// Display final stats
let finalStats = `
<h2>Quiz Completed!</h2>
<p>Total Questions: ${questions.length}</p>
<p>Correct Answers: ${correctAnswers}</p>
<p>Correctness: ${(correctAnswers / questions.length * 100).toFixed(2)}%</p>
`;
document.getElementById('stats').innerHTML = finalStats;
}
window.onload = function() {
loadSubjects();
};