-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
702 lines (622 loc) · 24.6 KB
/
script.js
File metadata and controls
702 lines (622 loc) · 24.6 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
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
// ===================================
// Global Variables
// ===================================
let currentTopic = '';
let currentDifficulty = 'medium';
let score = 0;
let totalQuestions = 0;
let startTime = null;
let timerInterval = null;
let currentQuestion = null;
let interviewHistory = []; // Store Q&A history for review
let isReviewMode = false;
// ===================================
// Question Bank (Sample Data)
// ===================================
const questionBank = {
'data-structures': [
{
question: "What is the time complexity of searching in a balanced BST?",
answer: "O(log n)",
hint: "Think about how the tree is divided at each step",
difficulty: "easy"
},
{
question: "Explain the difference between Stack and Queue",
answer: "Stack follows LIFO (Last In First Out), Queue follows FIFO (First In First Out)",
hint: "Think about how elements are added and removed",
difficulty: "easy"
},
{
question: "What is a hash collision and how do you handle it?",
answer: "Hash collision occurs when two keys hash to the same index. Can be handled using chaining or open addressing",
hint: "Consider what happens when two keys map to the same location",
difficulty: "medium"
},
{
question: "What is the difference between Array and Linked List?",
answer: "Arrays have fixed size and contiguous memory, Linked Lists are dynamic and use pointers to connect nodes",
hint: "Think about memory allocation and size flexibility",
difficulty: "easy"
},
{
question: "Explain Binary Search Tree properties",
answer: "In BST, left child is smaller than parent, right child is greater than parent, and this property holds for all nodes",
hint: "Consider the ordering of left and right subtrees",
difficulty: "medium"
}
],
'algorithms': [
{
question: "What is the time complexity of Quick Sort in the worst case?",
answer: "O(n²)",
hint: "Consider when the pivot is always the smallest or largest element",
difficulty: "medium"
},
{
question: "Explain the concept of Dynamic Programming",
answer: "Dynamic Programming is a technique to solve problems by breaking them into overlapping subproblems and storing results to avoid recomputation",
hint: "Think about memoization and optimal substructure",
difficulty: "hard"
},
{
question: "What is the time complexity of Merge Sort?",
answer: "O(n log n) in all cases",
hint: "It divides the array and merges sorted halves",
difficulty: "easy"
},
{
question: "Explain Breadth First Search (BFS)",
answer: "BFS explores graph level by level using a queue, visiting all neighbors before moving to next level",
hint: "Think about using a queue data structure",
difficulty: "medium"
},
{
question: "What is Greedy Algorithm?",
answer: "A greedy algorithm makes locally optimal choice at each step hoping to find global optimum",
hint: "Think about making the best choice at each step",
difficulty: "medium"
}
],
'operating-systems': [
{
question: "What is a deadlock?",
answer: "A deadlock is a situation where a set of processes are blocked because each process is holding a resource and waiting for another resource held by another process",
hint: "Think about circular waiting",
difficulty: "medium"
},
{
question: "Explain the difference between process and thread",
answer: "A process is an independent program in execution with its own memory space, while a thread is a lightweight unit of execution within a process that shares memory",
hint: "Consider memory sharing and independence",
difficulty: "easy"
},
{
question: "What are the four conditions for deadlock?",
answer: "Mutual Exclusion, Hold and Wait, No Preemption, and Circular Wait",
hint: "Think about necessary conditions that must all be present",
difficulty: "hard"
},
{
question: "Explain virtual memory",
answer: "Virtual memory is a memory management technique that uses hard disk space as extension of RAM, allowing larger programs to run",
hint: "Think about using disk as memory extension",
difficulty: "medium"
},
{
question: "What is context switching?",
answer: "Context switching is the process of storing and restoring the state of a process so execution can be resumed later",
hint: "Think about switching between processes",
difficulty: "easy"
}
],
'dbms': [
{
question: "What are ACID properties?",
answer: "Atomicity, Consistency, Isolation, Durability - properties that guarantee database transactions are processed reliably",
hint: "Think about transaction guarantees",
difficulty: "medium"
},
{
question: "Explain normalization and its purpose",
answer: "Normalization is the process of organizing data to reduce redundancy and improve data integrity",
hint: "Think about removing duplicate data",
difficulty: "medium"
},
{
question: "What is a primary key?",
answer: "A primary key is a unique identifier for a record in a table that cannot be null",
hint: "Think about unique identification",
difficulty: "easy"
},
{
question: "Difference between DELETE and TRUNCATE",
answer: "DELETE removes rows one by one and can be rolled back, TRUNCATE removes all rows at once and cannot be rolled back",
hint: "Think about rollback capability",
difficulty: "medium"
},
{
question: "What is a foreign key?",
answer: "A foreign key is a field that links to the primary key of another table, establishing relationships between tables",
hint: "Think about table relationships",
difficulty: "easy"
}
],
'networks': [
{
question: "What is the difference between TCP and UDP?",
answer: "TCP is connection-oriented and reliable, UDP is connectionless and faster but unreliable",
hint: "Think about reliability vs speed",
difficulty: "easy"
},
{
question: "Explain the OSI model layers",
answer: "Physical, Data Link, Network, Transport, Session, Presentation, Application - 7 layers of network communication",
hint: "Think about 7 layers from physical to application",
difficulty: "medium"
},
{
question: "What is DNS?",
answer: "Domain Name System translates domain names to IP addresses",
hint: "Think about converting names to numbers",
difficulty: "easy"
},
{
question: "What is HTTP and HTTPS difference?",
answer: "HTTPS is HTTP with SSL/TLS encryption for secure communication",
hint: "Think about security and encryption",
difficulty: "easy"
},
{
question: "Explain three-way handshake in TCP",
answer: "SYN from client, SYN-ACK from server, ACK from client - establishes TCP connection",
hint: "Think about connection establishment steps",
difficulty: "medium"
}
],
'oop': [
{
question: "What is polymorphism?",
answer: "Polymorphism is the ability of objects to take multiple forms, allowing methods to do different things based on the object calling them",
hint: "Think about method overriding and overloading",
difficulty: "medium"
},
{
question: "Explain encapsulation",
answer: "Encapsulation is wrapping data and methods together and hiding internal details from outside",
hint: "Think about data hiding",
difficulty: "easy"
},
{
question: "What is inheritance?",
answer: "Inheritance is a mechanism where a new class derives properties and methods from an existing class",
hint: "Think about parent-child relationship",
difficulty: "easy"
},
{
question: "Difference between abstract class and interface",
answer: "Abstract class can have implementation and variables, interface only has method signatures (in traditional OOP)",
hint: "Think about partial vs full abstraction",
difficulty: "medium"
},
{
question: "What is abstraction?",
answer: "Abstraction is hiding complex implementation details and showing only essential features",
hint: "Think about showing only what's necessary",
difficulty: "easy"
}
]
};
// ===================================
// DOM Elements
// ===================================
const welcomeScreen = document.getElementById('welcomeScreen');
const chatInterface = document.getElementById('chatInterface');
const resultsScreen = document.getElementById('resultsScreen');
const topicButtons = document.querySelectorAll('.topic-btn');
const difficultySelect = document.getElementById('difficulty');
const chatMessages = document.getElementById('chatMessages');
const userInput = document.getElementById('userInput');
const sendBtn = document.getElementById('sendBtn');
const backBtn = document.getElementById('backBtn');
const hintBtn = document.getElementById('hintBtn');
const skipBtn = document.getElementById('skipBtn');
const endBtn = document.getElementById('endBtn');
const reviewBtn = document.getElementById('reviewBtn');
const restartBtn = document.getElementById('restartBtn');
const scoreDisplay = document.getElementById('score');
const currentTopicDisplay = document.getElementById('currentTopic');
const timeElapsed = document.getElementById('timeElapsed');
// ===================================
// Event Listeners
// ===================================
topicButtons.forEach(btn => {
btn.addEventListener('click', () => {
currentTopic = btn.dataset.topic;
currentDifficulty = difficultySelect.value;
startInterview();
});
});
sendBtn.addEventListener('click', submitAnswer);
userInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitAnswer();
}
});
backBtn.addEventListener('click', backToHome);
hintBtn.addEventListener('click', showHint);
skipBtn.addEventListener('click', skipQuestion);
endBtn.addEventListener('click', endInterview);
restartBtn.addEventListener('click', backToHome);
reviewBtn.addEventListener('click', showReview);
// Auto-resize textarea
userInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 120) + 'px';
});
// ===================================
// Core Functions
// ===================================
function startInterview() {
// Reset variables
score = 0;
totalQuestions = 0;
startTime = Date.now();
interviewHistory = [];
isReviewMode = false;
// Update UI
welcomeScreen.style.display = 'none';
chatInterface.style.display = 'flex';
resultsScreen.style.display = 'none';
currentTopicDisplay.textContent = formatTopicName(currentTopic);
updateScore();
// Clear chat
chatMessages.innerHTML = '';
// Enable input and buttons
userInput.disabled = false;
sendBtn.disabled = false;
hintBtn.disabled = false;
skipBtn.disabled = false;
// Start timer
startTimer();
// Add welcome message
addBotMessage(`Welcome to the ${formatTopicName(currentTopic)} interview! Let's begin. 🚀`);
setTimeout(() => {
askQuestion();
}, 1000);
}
function startTimer() {
if (timerInterval) clearInterval(timerInterval);
timerInterval = setInterval(() => {
const elapsed = Math.floor((Date.now() - startTime) / 1000);
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
timeElapsed.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}, 1000);
}
function askQuestion() {
const questions = questionBank[currentTopic] || [];
if (questions.length === 0) {
addBotMessage("No questions available for this topic yet. Coming soon! 😊");
return;
}
// Get random question (avoid repeating if possible)
const availableQuestions = questions.filter(q => q !== currentQuestion);
const questionsToUse = availableQuestions.length > 0 ? availableQuestions : questions;
currentQuestion = questionsToUse[Math.floor(Math.random() * questionsToUse.length)];
totalQuestions++;
addBotMessage(`<strong>Question ${totalQuestions}:</strong><br><br>${currentQuestion.question}`);
userInput.focus();
}
function submitAnswer() {
const answer = userInput.value.trim();
if (!answer) {
alert('Please type an answer before submitting!');
return;
}
// Disable input while processing
userInput.disabled = true;
sendBtn.disabled = true;
// Add user message
addUserMessage(answer);
userInput.value = '';
userInput.style.height = 'auto';
// Evaluate answer after short delay
setTimeout(() => {
evaluateAnswer(answer);
userInput.disabled = false;
sendBtn.disabled = false;
userInput.focus();
}, 500);
}
function evaluateAnswer(userAnswer) {
if (!currentQuestion) return;
const correctAnswer = currentQuestion.answer.toLowerCase();
const userAnswerLower = userAnswer.toLowerCase();
// Simple keyword matching
const keywords = correctAnswer.split(' ').filter(word => word.length > 3);
const matchedKeywords = keywords.filter(keyword =>
userAnswerLower.includes(keyword.toLowerCase())
);
const similarity = keywords.length > 0 ? matchedKeywords.length / keywords.length : 0;
const isCorrect = similarity > 0.5;
if (isCorrect) {
score++;
addBotMessage(
`<strong>✅ Correct! Well done!</strong><br><em>Expected answer: ${currentQuestion.answer}</em>`,
'correct'
);
} else {
addBotMessage(
`<strong>❌ Not quite right.</strong><br><em>The correct answer is: ${currentQuestion.answer}</em>`,
'incorrect'
);
}
// Save to history
interviewHistory.push({
questionNumber: totalQuestions,
question: currentQuestion.question,
userAnswer: userAnswer,
correctAnswer: currentQuestion.answer,
isCorrect: isCorrect
});
updateScore();
// Ask next question after delay
setTimeout(() => {
if (totalQuestions < 5) {
askQuestion();
} else {
setTimeout(endInterview, 1000);
}
}, 3000);
}
function showHint() {
if (currentQuestion && currentQuestion.hint) {
addBotMessage(`<strong>💡 Hint:</strong><br>${currentQuestion.hint}`);
} else {
addBotMessage(`Sorry, no hint available for this question.`);
}
}
function skipQuestion() {
if (!currentQuestion) return;
// Save to history as skipped
interviewHistory.push({
questionNumber: totalQuestions,
question: currentQuestion.question,
userAnswer: "Skipped",
correctAnswer: currentQuestion.answer,
isCorrect: false
});
addBotMessage(`<strong>⏭️ Question skipped.</strong><br><em>The answer was: ${currentQuestion.answer}</em>`);
setTimeout(() => {
if (totalQuestions < 5) {
askQuestion();
} else {
setTimeout(endInterview, 1000);
}
}, 2000);
}
function endInterview() {
clearInterval(timerInterval);
// Disable input
userInput.disabled = true;
sendBtn.disabled = true;
hintBtn.disabled = true;
skipBtn.disabled = true;
chatInterface.style.display = 'none';
resultsScreen.style.display = 'flex';
// Calculate stats
const percentage = totalQuestions > 0 ? Math.round((score / totalQuestions) * 100) : 0;
const timeTaken = timeElapsed.textContent;
// Update results
document.getElementById('finalScore').textContent = `${score}/${totalQuestions}`;
document.getElementById('percentage').textContent = `${percentage}%`;
document.getElementById('totalTime').textContent = timeTaken;
// Performance message
let message = '';
if (percentage >= 80) {
message = '🎉 Excellent! You have a strong understanding!';
} else if (percentage >= 60) {
message = '👍 Good job! Keep practicing to improve further.';
} else if (percentage >= 40) {
message = '📚 Not bad! Review the concepts and try again.';
} else {
message = '💪 Keep learning! Practice makes perfect.';
}
document.getElementById('performanceMessage').textContent = message;
}
function showReview() {
isReviewMode = true;
resultsScreen.style.display = 'none';
chatInterface.style.display = 'flex';
// Clear chat and reset scroll
chatMessages.innerHTML = '';
chatMessages.scrollTop = 0;
// Disable input in review mode
userInput.disabled = true;
sendBtn.disabled = true;
hintBtn.disabled = true;
skipBtn.disabled = true;
// Update header
currentTopicDisplay.textContent = `Review - ${formatTopicName(currentTopic)}`;
// Add review header
addBotMessage(`<strong>📋 Interview Review</strong><br><br>Here's a detailed review of your performance. Study each question and answer carefully.`);
// Display each Q&A from history with better timing
let delay = 1000;
interviewHistory.forEach((item, index) => {
setTimeout(() => {
// Question
addBotMessage(`<strong>Question ${item.questionNumber}:</strong><br><br>${item.question}`);
setTimeout(() => {
// User's answer
if (item.userAnswer === "Skipped") {
addBotMessage(`<strong>⏭️ You skipped this question</strong>`);
} else {
addUserMessage(item.userAnswer);
}
setTimeout(() => {
// Feedback with correct answer
if (item.isCorrect) {
addBotMessage(
`<strong>✅ Your answer was correct!</strong><br><br><em>Expected answer: ${item.correctAnswer}</em>`,
'correct'
);
} else {
addBotMessage(
`<strong>❌ Your answer was ${item.userAnswer === "Skipped" ? "skipped" : "incorrect"}.</strong><br><br><em>Correct answer: ${item.correctAnswer}</em>`,
'incorrect'
);
}
// Force scroll to bottom
forceScrollToBottom();
}, 500);
}, 500);
}, delay);
delay += 2000; // Increment delay for next question
});
// Add final summary
setTimeout(() => {
const percentage = totalQuestions > 0 ? Math.round((score / totalQuestions) * 100) : 0;
addBotMessage(
`<strong>🎯 Review Complete!</strong><br><br>
<strong>Final Score:</strong> ${score}/${totalQuestions}<br>
<strong>Accuracy:</strong> ${percentage}%<br>
<strong>Time Taken:</strong> ${timeElapsed.textContent}<br><br>
Click "Back" to return home or start a new interview to improve your score!`
);
forceScrollToBottom();
}, delay + 1000);
}
function backToHome() {
clearInterval(timerInterval);
chatInterface.style.display = 'none';
resultsScreen.style.display = 'none';
welcomeScreen.style.display = 'flex';
// Reset everything
score = 0;
totalQuestions = 0;
currentQuestion = null;
interviewHistory = [];
isReviewMode = false;
chatMessages.innerHTML = '';
updateScore();
timeElapsed.textContent = '00:00';
// Re-enable input
userInput.disabled = false;
sendBtn.disabled = false;
hintBtn.disabled = false;
skipBtn.disabled = false;
userInput.value = '';
}
// ===================================
// Message Functions with Fixed Scrolling
// ===================================
function addBotMessage(message, feedbackType = '') {
const messageDiv = document.createElement('div');
messageDiv.className = 'message bot';
let contentClass = 'message-content';
if (feedbackType === 'correct') contentClass += ' feedback correct';
if (feedbackType === 'incorrect') contentClass += ' feedback incorrect';
messageDiv.innerHTML = `
<div class="message-avatar">
<i class="fas fa-robot"></i>
</div>
<div class="${contentClass}">
${message}
</div>
`;
chatMessages.appendChild(messageDiv);
// Force scroll with multiple methods for browser compatibility
requestAnimationFrame(() => {
chatMessages.scrollTop = chatMessages.scrollHeight;
chatMessages.scrollIntoView({ behavior: 'smooth', block: 'end' });
});
}
function addUserMessage(message) {
const messageDiv = document.createElement('div');
messageDiv.className = 'message user';
// Escape HTML to prevent XSS
const escapedMessage = message
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n/g, '<br>');
messageDiv.innerHTML = `
<div class="message-content">
${escapedMessage}
</div>
<div class="message-avatar">
<i class="fas fa-user"></i>
</div>
`;
chatMessages.appendChild(messageDiv);
// Force scroll with multiple methods for browser compatibility
requestAnimationFrame(() => {
chatMessages.scrollTop = chatMessages.scrollHeight;
chatMessages.scrollIntoView({ behavior: 'smooth', block: 'end' });
});
}
// Force scroll function for review mode
function forceScrollToBottom() {
// Multiple scroll methods for cross-browser compatibility
setTimeout(() => {
// Method 1: Direct scroll
chatMessages.scrollTop = chatMessages.scrollHeight;
// Method 2: ScrollTo
chatMessages.scrollTo({
top: chatMessages.scrollHeight,
behavior: 'smooth'
});
// Method 3: ScrollIntoView
const lastMessage = chatMessages.lastElementChild;
if (lastMessage) {
lastMessage.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
}, 100);
}
// ===================================
// Utility Functions
// ===================================
function updateScore() {
scoreDisplay.textContent = `${score}/${totalQuestions}`;
}
function formatTopicName(topic) {
return topic.split('-').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
}
// ===================================
// Initialization
// ===================================
document.addEventListener('DOMContentLoaded', () => {
console.log('🚀 CSE Interview Chatbot initialized successfully!');
console.log('Version: 2.0 - With Review & Colorful UI');
// Set initial states
welcomeScreen.style.display = 'flex';
chatInterface.style.display = 'none';
resultsScreen.style.display = 'none';
// Add animation classes if needed
if (welcomeScreen) {
welcomeScreen.classList.add('animated');
}
});
// ===================================
// Error Handling
// ===================================
window.addEventListener('error', (e) => {
console.error('Application Error:', e.error);
// You can add user-friendly error messages here
});
// ===================================
// Export for testing (if needed)
// ===================================
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
startInterview,
submitAnswer,
evaluateAnswer,
showReview,
questionBank
};
}