forked from nrupuld/random-variable-2019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquiz.js
More file actions
98 lines (80 loc) · 2.84 KB
/
Copy pathquiz.js
File metadata and controls
98 lines (80 loc) · 2.84 KB
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
// Define the Quiz class
class Quiz {
constructor() {
this.questions = []; // Array to store questions
this.sessions = {}; // Object to map userId to their quiz session data
this.results = {}; // Object to store quiz results for users
}
// Method to add a question to the quiz
addQuestion(questionText, options, correctOption) {
const question = {
questionText,
options,
correctOption
};
this.questions.push(question);
}
// Method to start a quiz session for a specific user
startQuiz(userId) {
this.sessions[userId] = {
currentQuestionIndex: 0,
answers: []
};
}
// Method to submit answers and calculate the score
submitAnswers(userId, userAnswers) {
const session = this.sessions[userId];
if (!session) {
console.log(`No quiz session found for userId: ${userId}`);
return;
}
let score = 0;
session.answers = userAnswers;
userAnswers.forEach((answer, index) => {
if (answer === this.questions[index].correctOption) {
score++;
}
});
this.storeResults(userId, score);
}
// Method to display correct and incorrect answers for a specific user
displayResults(userId) {
const session = this.sessions[userId];
if (!session) {
console.log(`No quiz session found for userId: ${userId}`);
return;
}
const results = {
correctAnswers: [],
incorrectAnswers: []
};
session.answers.forEach((answer, index) => {
if (answer === this.questions[index].correctOption) {
results.correctAnswers.push(this.questions[index]);
} else {
results.incorrectAnswers.push(this.questions[index]);
}
});
return results;
}
// Method to store the user's quiz results
storeResults(userId, score) {
this.results[userId] = score;
}
}
// Example usage
const quiz = new Quiz();
// Adding questions to the quiz
quiz.addQuestion("What is the capital of France?", ["Paris", "London", "Berlin", "Madrid"], 0);
quiz.addQuestion("What is 2 + 2?", ["3", "4", "5", "6"], 1);
quiz.addQuestion("What is the capital of Japan?", ["Beijing", "Seoul", "Tokyo", "Bangkok"], 2);
// Starting a quiz session for a user
quiz.startQuiz("user1");
// Submitting answers for the user
quiz.submitAnswers("user1", [0, 1, 2]);
// Displaying results for the user
const results = quiz.displayResults("user1");
console.log(results); // Output: { correctAnswers: [...], incorrectAnswers: [...] }
// Storing the user's quiz results
quiz.storeResults("user1", 3);
console.log(quiz.results); // Output: { user1: 3 }