-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
863 lines (779 loc) · 36.7 KB
/
Copy pathapp.js
File metadata and controls
863 lines (779 loc) · 36.7 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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/* ===== Sanfoundry Java MCQ Quiz — engine ===== */
(function () {
'use strict';
var DATA = (window.QUIZ_DATA || { meta: {}, questions: [] });
var ALL = DATA.questions;
var $ = function (id) { return document.getElementById(id); };
/* ---------------- state ---------------- */
var S = {
cats: {}, // category -> bool
topics: {}, // "category|topic" -> bool
qtype: 'all', // 'all' | 'code' | 'text'
len: 25,
perPage: 30,
mode: 'practice',
shuffleQ: true,
shuffleO: false,
timer: false,
list: [], // [{ q, opts }]
answers: [],
revealed: [],
page: 0,
startedAt: 0,
elapsed: 0,
tick: null,
reviewWrongOnly: false
};
var LS_THEME = 'jq_theme';
var tkey = function (cat, topic) { return cat + '|' + topic; };
/* ---------------- helpers ---------------- */
function esc(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
.replace(/"/g, '"');
}
var KW = ('abstract assert boolean break byte case catch char class const continue default do ' +
'double else enum extends final finally float for goto if implements import instanceof int ' +
'interface long native new package private protected public return short static strictfp super ' +
'switch synchronized this throw throws transient try void volatile while true false null var record ' +
'yield sealed permits').split(' ');
var KWSET = {};
KW.forEach(function (k) { KWSET[k] = 1; });
// Single pass over the escaped source. Strings and comments are matched before
// identifiers, so keywords/numbers inside them are never re-highlighted.
var TOKEN_RE = /("(?:\\.|&(?!quot;)|[^&\\])*?"|'(?:\\.|[^'\\])*?')|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|([A-Za-z_$][A-Za-z0-9_$]*)|(\d+(?:\.\d+)?[fFdDlL]?)/g;
function highlight(code) {
return esc(code).replace(TOKEN_RE, function (m, str, cmt, ident, num) {
if (str) return '<span class="str">' + str + '</span>';
if (cmt) return '<span class="cmt">' + cmt + '</span>';
if (ident) return KWSET[ident] ? '<span class="kw">' + ident + '</span>' : ident;
if (num) return '<span class="num">' + num + '</span>';
return m;
});
}
// Many blocks are program *output*, not source. Highlighting those turns ordinary
// words ("case", "class") into fake keywords, so only syntax-colour real Java.
function looksLikeSource(c) {
return /[;{}]/.test(c) ||
/^\s*(import|package|public|private|protected|class|interface|enum)\b/m.test(c);
}
function codeHTML(arr) {
if (!arr || !arr.length) return '';
return arr.map(function (c) {
return '<pre class="code">' + (looksLikeSource(c) ? highlight(c) : esc(c)) + '</pre>';
}).join('');
}
function shuffle(a) {
for (var i = a.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = a[i]; a[i] = a[j]; a[j] = t;
}
return a;
}
function fmtTime(ms) {
var s = Math.floor(ms / 1000), m = Math.floor(s / 60);
return m + ':' + (s % 60 < 10 ? '0' : '') + (s % 60);
}
function show(screen) {
['screenStart', 'screenQuiz', 'screenResult'].forEach(function (id) {
$(id).classList.toggle('hide', id !== screen);
});
$('btnQuit').classList.toggle('hide', screen !== 'screenQuiz');
window.scrollTo(0, 0);
}
/* ---------------- theme ---------------- */
function setTheme(t) {
document.documentElement.setAttribute('data-theme', t);
$('btnTheme').textContent = t === 'dark' ? 'Light' : 'Dark';
try { localStorage.setItem(LS_THEME, t); } catch (e) { }
}
$('btnTheme').onclick = function () {
setTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark');
};
try {
var saved = localStorage.getItem(LS_THEME);
setTheme(saved || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
} catch (e) { setTheme('light'); }
/* ---------------- start screen ---------------- */
var CATS = DATA.meta.categories || [];
var TOPICS_BY_CAT = {};
// A "code question" shows a Java snippet you must read to answer — either in the
// question body or inside the options. Explanation/output code doesn't count.
function isCode(q) {
return !!(q.code && q.code.length) || q.opts.some(function (o) { return o.c; });
}
function typeOf(q) { return isCode(q) ? 'code' : 'text'; }
// counts per filter type, so the numbers on screen always match what you'd get
var COUNT = { all: {}, code: {}, text: {} }; // "cat|topic" -> n
var CATN = { all: {}, code: {}, text: {} }; // category -> n
ALL.forEach(function (q) {
var k = tkey(q.cat, q.topic), t = typeOf(q);
['all', t].forEach(function (b) {
COUNT[b][k] = (COUNT[b][k] || 0) + 1;
CATN[b][q.cat] = (CATN[b][q.cat] || 0) + 1;
});
(TOPICS_BY_CAT[q.cat] = TOPICS_BY_CAT[q.cat] || {})[q.topic] = true;
});
function matchesType(q) { return S.qtype === 'all' || typeOf(q) === S.qtype; }
function nTopic(c, t) { return COUNT[S.qtype][tkey(c, t)] || 0; }
function nCat(c) { return CATN[S.qtype][c] || 0; }
var catButtons = {};
/* preset topic bundles — generated from the bank, keys are "category|topic" */
var PRESETS = /*__PRESETS__*/[
{"name": "Java basics + all OOP", "n": 725, "topics": ["Interview & Aptitude|Freshers Experienced", "Core Java|JDK-JRE-JIT-JVM", "Core Java|Literals & Variables", "Core Java|Character and Boolean Datatypes", "Core Java|Integer and Floating Datatypes", "Core Java|Type Conversions, Promotions and Castings", "Core Java|Control Statements", "Core Java|Arithmetic Operators", "Core Java|Relational Operators and Boolean Logic Operators", "Core Java|Assignment Operators and Operator Precedence", "Core Java|Bitwise Operators", "Core Java|Command Line Arguments", "Interview & Aptitude|Command Line Arguments – 2", "Core Java|Core Java API Packages", "Core Java|Coding Best Practices", "Core Java|Class Fundamentals & Object Declaration", "Core Java|Object Class", "OOP using Java|Object Class", "Core Java|Object & Math Classes", "Core Java|Java.lang – Class", "Core Java|Access Control", "Core Java|Packages", "OOP using Java|Assigning Objects", "OOP using Java|Data Members", "OOP using Java|Member Functions", "OOP using Java|Memory Allocation", "OOP using Java|Inner Class", "OOP using Java|Nested Class", "OOP using Java|Static Class", "OOP using Java|Final Class", "OOP using Java|Generic Class", "OOP using Java|Wrapper Class", "Core Java|Constructor", "Core Java|Constructors & Garbage Collection", "OOP using Java|Constructors", "OOP using Java|Types of Constructors", "OOP using Java|Constructor Overloading", "OOP using Java|Copy Constructors", "Core Java|Inheritance", "Core Java|Abstract Class", "Core Java|Interfaces", "Core Java|Method Overriding", "OOP using Java|Base Class", "OOP using Java|Derived Class", "OOP using Java|Single Level Inheritance", "OOP using Java|Multilevel Inheritance", "OOP using Java|Hierarchical Inheritance", "OOP using Java|Hybrid Inheritance", "OOP using Java|Types of Inheritance", "OOP using Java|Method Overriding", "Core Java|OOPs", "Core Java|Overloading Methods & Argument Passing", "Core Java|Methods", "Core Java|Methods Taking Parameters", "Interview & Aptitude|Methods Taking Parameters", "OOP using Java|Method Overloading", "Interview & Aptitude|Liskov’s Principle", "OOP using Java|This Keyword", "Core Java|Arrays and Static Keyword", "Core Java|Keyword Finally and Built in Exceptions"]},
{"name": "Java basics & history", "n": 203, "topics": ["Interview & Aptitude|Freshers Experienced", "Core Java|JDK-JRE-JIT-JVM", "Core Java|Literals & Variables", "Core Java|Character and Boolean Datatypes", "Core Java|Integer and Floating Datatypes", "Core Java|Type Conversions, Promotions and Castings", "Core Java|Control Statements", "Core Java|Arithmetic Operators", "Core Java|Relational Operators and Boolean Logic Operators", "Core Java|Assignment Operators and Operator Precedence", "Core Java|Bitwise Operators", "Core Java|Command Line Arguments", "Interview & Aptitude|Command Line Arguments – 2", "Core Java|Core Java API Packages", "Core Java|Coding Best Practices"]},
{"name": "Classes & objects", "n": 195, "topics": ["Core Java|Class Fundamentals & Object Declaration", "Core Java|Object Class", "OOP using Java|Object Class", "Core Java|Object & Math Classes", "Core Java|Java.lang – Class", "Core Java|Access Control", "Core Java|Packages", "OOP using Java|Assigning Objects", "OOP using Java|Data Members", "OOP using Java|Member Functions", "OOP using Java|Memory Allocation", "OOP using Java|Inner Class", "OOP using Java|Nested Class", "OOP using Java|Static Class", "OOP using Java|Final Class", "OOP using Java|Generic Class", "OOP using Java|Wrapper Class"]},
{"name": "Constructors", "n": 80, "topics": ["Core Java|Constructor", "Core Java|Constructors & Garbage Collection", "OOP using Java|Constructors", "OOP using Java|Types of Constructors", "OOP using Java|Constructor Overloading", "OOP using Java|Copy Constructors"]},
{"name": "Inheritance & abstraction", "n": 144, "topics": ["Core Java|Inheritance", "Core Java|Abstract Class", "Core Java|Interfaces", "Core Java|Method Overriding", "OOP using Java|Base Class", "OOP using Java|Derived Class", "OOP using Java|Single Level Inheritance", "OOP using Java|Multilevel Inheritance", "OOP using Java|Hierarchical Inheritance", "OOP using Java|Hybrid Inheritance", "OOP using Java|Types of Inheritance", "OOP using Java|Method Overriding"]},
{"name": "Polymorphism & methods", "n": 69, "topics": ["Core Java|OOPs", "Core Java|Overloading Methods & Argument Passing", "Core Java|Methods", "Core Java|Methods Taking Parameters", "Interview & Aptitude|Methods Taking Parameters", "OOP using Java|Method Overloading", "Interview & Aptitude|Liskov’s Principle"]},
{"name": "Java keywords", "n": 34, "topics": ["OOP using Java|This Keyword", "Core Java|Arrays and Static Keyword", "Core Java|Keyword Finally and Built in Exceptions"]}
];
function applyPreset(keys) {
Object.keys(S.topics).forEach(function (k) { S.topics[k] = false; });
keys.forEach(function (k) { S.topics[k] = true; });
CATS.forEach(function (c) {
S.cats[c] = keys.some(function (k) { return k.indexOf(c + '|') === 0; });
});
$('topicSearch').value = '';
syncCatChips();
syncCatLabels();
renderTopics();
updateStartHint();
$('presetChips').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
function buildPresets() {
var pc = $('presetChips');
pc.innerHTML = '';
PRESETS.forEach(function (p, idx) {
var b = document.createElement('button');
b.className = 'chip' + (idx === 0 ? ' primary' : '');
b.innerHTML = esc(p.name) + '<span class="n">' + p.n + '</span>';
b.onclick = function () {
applyPreset(p.topics);
Array.prototype.forEach.call(pc.children, function (x) { x.classList.remove('on'); });
b.classList.add('on');
};
pc.appendChild(b);
});
}
function syncCatLabels() {
CATS.forEach(function (c) {
var n = nCat(c);
var b = catButtons[c];
b.innerHTML = esc(c) + '<span class="n">' + n + '</span>';
// e.g. "OOP using Java" has no theory questions at all — don't offer an empty quiz
b.disabled = n === 0;
b.title = n === 0 ? c + ' has no ' +
(S.qtype === 'code' ? 'code' : 'theory') + ' questions' : '';
});
}
function setCatTopics(c, on) {
Object.keys(TOPICS_BY_CAT[c] || {}).forEach(function (t) { S.topics[tkey(c, t)] = on; });
}
function syncCatChips() {
CATS.forEach(function (c) { catButtons[c].classList.toggle('on', !!S.cats[c]); });
}
// any manual change to categories/topics means the selection is no longer a preset
function clearPresetHighlight() {
Array.prototype.forEach.call($('presetChips').children, function (x) {
x.classList.remove('on');
});
}
function buildStart() {
$('stTotal').textContent = ALL.length.toLocaleString();
$('stTopics').textContent = (DATA.meta.topics || []).length;
$('stCode').textContent = ALL.filter(function (q) {
return q.code || q.opts.some(function (o) { return o.c; });
}).length;
$('stExp').textContent = ALL.filter(function (q) { return q.exp; }).length;
var cc = $('catChips');
cc.innerHTML = '';
CATS.forEach(function (c) {
S.cats[c] = true;
setCatTopics(c, true);
var b = document.createElement('button');
b.className = 'chip on';
b.onclick = function () {
var allOn = CATS.every(function (x) { return S.cats[x]; });
if (allOn) {
// Everything is on -> "solo" this category, which is what clicking one means.
CATS.forEach(function (x) { S.cats[x] = (x === c); setCatTopics(x, x === c); });
} else {
S.cats[c] = !S.cats[c];
setCatTopics(c, S.cats[c]);
if (!CATS.some(function (x) { return S.cats[x]; })) { // never leave it empty
CATS.forEach(function (x) { S.cats[x] = true; setCatTopics(x, true); });
}
}
clearPresetHighlight();
syncCatChips();
renderTopics($('topicSearch').value);
updateStartHint();
};
catButtons[c] = b;
cc.appendChild(b);
});
// question-type filter — changing it re-counts every category and topic
var tc = $('typeChips');
tc.innerHTML = '';
[['all', 'All questions'], ['code', 'Code output only'], ['text', 'Theory only']]
.forEach(function (pair) {
var v = pair[0], label = pair[1];
var b = document.createElement('button');
b.className = 'chip' + (v === 'all' ? ' on' : '');
b.dataset.t = v;
var n = v === 'all' ? ALL.length
: ALL.reduce(function (a, q) { return a + (typeOf(q) === v ? 1 : 0); }, 0);
b.innerHTML = esc(label) + '<span class="n">' + n + '</span>';
b.onclick = function () {
S.qtype = v;
Array.prototype.forEach.call(tc.children, function (x) { x.classList.remove('on'); });
b.classList.add('on');
syncCatLabels();
renderTopics($('topicSearch').value);
updateStartHint();
};
tc.appendChild(b);
});
chipRow('lenChips', [10, 25, 50, 100, 200, 'All'], 25, function (v) { S.len = v; });
chipRow('pageChips', [10, 20, 30, 50], 30, function (v) { S.perPage = v; });
Array.prototype.forEach.call($('modeChips').children, function (b) {
b.onclick = function () {
S.mode = b.dataset.mode;
Array.prototype.forEach.call($('modeChips').children, function (x) { x.classList.remove('on'); });
b.classList.add('on');
};
});
buildPresets();
syncCatLabels();
renderTopics();
updateStartHint();
}
function chipRow(id, values, def, onPick) {
var el = $(id);
el.innerHTML = '';
values.forEach(function (v) {
var b = document.createElement('button');
b.className = 'chip' + (v === def ? ' on' : '');
b.textContent = v;
b.onclick = function () {
onPick(v);
Array.prototype.forEach.call(el.children, function (x) { x.classList.remove('on'); });
b.classList.add('on');
updateStartHint();
};
el.appendChild(b);
});
}
function renderTopics(filter) {
var box = $('topicBox');
box.innerHTML = '';
var f = (filter || '').toLowerCase();
CATS.forEach(function (c) {
if (!S.cats[c]) return; // hide topics of unselected categories
var ts = Object.keys(TOPICS_BY_CAT[c] || {}).sort()
.filter(function (t) { return !f || t.toLowerCase().indexOf(f) >= 0; })
.filter(function (t) { return nTopic(c, t) > 0; }); // hide topics with none of this type
if (!ts.length) return;
var h = document.createElement('div');
h.className = 'topic-cat';
h.textContent = c;
box.appendChild(h);
ts.forEach(function (t) {
var k = tkey(c, t);
var row = document.createElement('label');
row.className = 'topic-row';
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = !!S.topics[k];
cb.onchange = function () {
S.topics[k] = cb.checked; clearPresetHighlight(); updateStartHint();
};
var span = document.createElement('span');
span.textContent = t;
var n = document.createElement('span');
n.className = 'n';
n.textContent = nTopic(c, t);
row.appendChild(cb); row.appendChild(span); row.appendChild(n);
box.appendChild(row);
});
});
if (!box.children.length) {
box.innerHTML = '<div class="topic-cat">No topics match that filter</div>';
}
}
function pool() {
return ALL.filter(function (q) {
return S.cats[q.cat] && S.topics[tkey(q.cat, q.topic)] && matchesType(q);
});
}
function updateStartHint() {
var n = pool().length;
// only count topics that actually contribute under the current category/type filters
var sel = 0;
CATS.forEach(function (c) {
if (!S.cats[c]) return;
Object.keys(TOPICS_BY_CAT[c] || {}).forEach(function (t) {
if (S.topics[tkey(c, t)] && nTopic(c, t) > 0) sel++;
});
});
$('topicCount').textContent = sel + ' selected';
var take = S.len === 'All' ? n : Math.min(S.len, n);
var kind = S.qtype === 'code' ? ' code' : S.qtype === 'text' ? ' theory' : '';
$('startHint').textContent = n
? take + ' of ' + n + kind + ' questions' +
(take > S.perPage ? ' · ' + S.perPage + ' per page' : '')
: 'No questions match — widen the filters';
$('btnStart').disabled = n === 0;
}
$('topicSearch').oninput = function () { renderTopics(this.value); };
$('btnAllTopics').onclick = function () {
clearPresetHighlight();
CATS.forEach(function (c) { S.cats[c] = true; setCatTopics(c, true); });
syncCatChips();
renderTopics($('topicSearch').value);
updateStartHint();
};
$('btnNoTopics').onclick = function () {
clearPresetHighlight();
Object.keys(S.topics).forEach(function (k) { S.topics[k] = false; });
renderTopics($('topicSearch').value);
updateStartHint();
};
/* ---------------- quiz (scrolling pages) ---------------- */
function startQuiz(list) {
S.shuffleQ = $('optShuffleQ').checked;
S.shuffleO = $('optShuffleO').checked;
S.timer = $('optTimer').checked;
if (!list) {
list = pool().slice();
if (S.shuffleQ) shuffle(list);
if (S.len !== 'All') list = list.slice(0, S.len);
}
S.list = list.map(function (q) {
var opts = q.opts.slice();
if (S.shuffleO) shuffle(opts);
return { q: q, opts: opts };
});
S.answers = new Array(S.list.length).fill(null);
S.revealed = new Array(S.list.length).fill(false);
S.page = 0;
S.startedAt = Date.now();
S.elapsed = 0;
if (S.tick) clearInterval(S.tick);
if (S.timer) {
S.tick = setInterval(function () {
$('qTimer').textContent = fmtTime(Date.now() - S.startedAt);
}, 500);
}
$('qTimer').textContent = S.timer ? '0:00' : '';
show('screenQuiz');
renderPage();
}
function pageBounds() {
var from = S.page * S.perPage;
return [from, Math.min(from + S.perPage, S.list.length)];
}
function questionHTML(i) {
var item = S.list[i], q = item.q;
var revealed = S.revealed[i], chosen = S.answers[i];
var opts = item.opts.map(function (o, idx) {
var cls = 'opt';
if (revealed) {
if (o.k === q.ans) cls += ' correct';
else if (o.k === chosen) cls += ' wrong';
} else if (o.k === chosen) {
cls += ' sel';
}
var mark = revealed && o.k === q.ans ? '<span class="mark">✓</span>'
: (revealed && o.k === chosen ? '<span class="mark">✕</span>' : '');
return '<button class="' + cls + '" data-i="' + i + '" data-k="' + o.k + '"' +
(revealed ? ' disabled' : '') + '>' +
'<span class="key">' + String.fromCharCode(65 + idx) + '</span>' +
'<span class="txt">' + esc(o.t) + codeHTML(o.c) + '</span>' + mark + '</button>';
}).join('');
var fb = '';
if (revealed) {
var right = chosen === q.ans;
fb = '<div class="explain">' +
'<div class="verdict ' + (right ? 'ok' : 'bad') + '">' +
(right ? 'Correct' : (chosen ? 'Incorrect' : 'Skipped')) +
' — Sanfoundry answer: ' + q.ans.toUpperCase() + '</div>' +
(q.exp ? '<div class="lbl">Explanation</div><p>' + esc(q.exp) + '</p>' : '') +
(q.expCode ? '<div class="lbl">Output</div>' + codeHTML(q.expCode) : '') +
'<div class="src">Source: <a href="' + esc(q.src) + '" target="_blank" rel="noopener">' +
esc(q.src) + '</a></div></div>';
}
return '<div class="card qcard" id="qc' + i + '">' +
'<div class="qhead">' +
'<span class="qn">' + (i + 1) + '</span>' +
'<span class="badge">' + esc(q.topic) + '</span>' +
'<span class="badge plain">' + esc(q.cat) + '</span>' +
'</div>' +
(q.q ? '<p class="qtext">' + esc(q.q) + '</p>' : '') +
codeHTML(q.code) +
'<div class="opts">' + opts + '</div>' +
'<div class="fb">' + fb + '</div>' +
'</div>';
}
function renderPage() {
var b = pageBounds(), from = b[0], to = b[1];
var html = '';
for (var i = from; i < to; i++) html += questionHTML(i);
$('qList').innerHTML = html;
var pages = Math.max(1, Math.ceil(S.list.length / S.perPage));
$('qPageInfo').textContent = 'Page ' + (S.page + 1) + ' of ' + pages +
' · Q' + (from + 1) + '–' + to + ' of ' + S.list.length;
var lastPage = S.page >= pages - 1;
$('btnPrevPage').classList.toggle('hide', S.page === 0);
$('btnNextPage').classList.toggle('hide', lastPage);
$('btnNextPage').textContent = 'Next ' + Math.min(S.perPage, S.list.length - to) + ' →';
$('btnFinish').className = lastPage ? 'btn' : 'btn ghost';
$('pageHint').textContent = lastPage ? 'Last page' : 'Scroll down to answer, then load the next page';
updateProgress();
window.scrollTo(0, 0);
}
function updateProgress() {
var done = S.answers.reduce(function (n, a) { return n + (a != null ? 1 : 0); }, 0);
$('qAnswered').textContent = done + ' / ' + S.list.length + ' answered';
$('qProgress').style.width = (S.list.length ? done / S.list.length * 100 : 0) + '%';
}
// one delegated listener for every option button on the page
$('qList').addEventListener('click', function (e) {
var btn = e.target.closest ? e.target.closest('.opt') : null;
if (!btn || btn.disabled) return;
var i = +btn.dataset.i, k = btn.dataset.k;
if (S.revealed[i]) return;
S.answers[i] = k;
if (S.mode === 'practice') S.revealed[i] = true;
// re-render just this card so scroll position is preserved
var card = $('qc' + i);
if (card) card.outerHTML = questionHTML(i);
updateProgress();
});
$('btnNextPage').onclick = function () {
var pages = Math.ceil(S.list.length / S.perPage);
if (S.page < pages - 1) { S.page++; renderPage(); }
};
$('btnPrevPage').onclick = function () {
if (S.page > 0) { S.page--; renderPage(); }
};
$('btnFinish').onclick = function () {
var done = S.answers.reduce(function (n, a) { return n + (a != null ? 1 : 0); }, 0);
if (done < S.list.length &&
!confirm((S.list.length - done) + ' question(s) still unanswered. Finish anyway?')) return;
finish();
};
$('btnQuit').onclick = function () {
if (confirm('Quit this quiz? Progress will be lost.')) {
if (S.tick) clearInterval(S.tick);
show('screenStart');
}
};
/* ---------------- results ---------------- */
function finish() {
if (S.tick) clearInterval(S.tick);
S.elapsed = Date.now() - S.startedAt;
var ok = 0, bad = 0, skip = 0;
S.list.forEach(function (it, i) {
var a = S.answers[i];
if (a == null) skip++;
else if (a === it.q.ans) ok++;
else bad++;
});
var pct = S.list.length ? Math.round(ok / S.list.length * 100) : 0;
$('rsOk').textContent = ok;
$('rsBad').textContent = bad;
$('rsSkip').textContent = skip;
$('rsTime').textContent = fmtTime(S.elapsed);
$('rsPct').textContent = pct + '%';
$('rsGrade').textContent =
pct >= 90 ? 'Excellent' : pct >= 75 ? 'Strong' : pct >= 60 ? 'Decent' :
pct >= 40 ? 'Keep going' : 'Needs work';
var ring = $('ring');
ring.style.setProperty('--p', pct);
ring.style.setProperty('--c', pct >= 60 ? 'var(--ok)' : pct >= 40 ? 'var(--accent)' : 'var(--bad)');
var byTopic = {};
S.list.forEach(function (it, i) {
var t = it.q.topic;
byTopic[t] = byTopic[t] || { ok: 0, n: 0 };
byTopic[t].n++;
if (S.answers[i] === it.q.ans) byTopic[t].ok++;
});
var rows = Object.keys(byTopic).map(function (t) {
return { t: t, ok: byTopic[t].ok, n: byTopic[t].n, p: byTopic[t].ok / byTopic[t].n };
}).sort(function (a, b) { return a.p - b.p || b.n - a.n; });
$('cardBreakdown').classList.toggle('hide', rows.length < 2);
$('rsBars').innerHTML = rows.map(function (r) {
return '<div class="bar-row">' +
'<span class="nm" title="' + esc(r.t) + '">' + esc(r.t) + '</span>' +
'<span class="bar"><i style="width:' + (r.p * 100) + '%;background:' +
(r.p >= .6 ? 'var(--ok)' : r.p >= .4 ? 'var(--accent)' : 'var(--bad)') + '"></i></span>' +
'<span class="pc">' + r.ok + '/' + r.n + '</span></div>';
}).join('');
renderReview();
$('btnRetryWrong').classList.toggle('hide', bad + skip === 0);
show('screenResult');
}
function renderReview() {
var out = [];
S.list.forEach(function (it, i) {
var q = it.q, a = S.answers[i];
var state = a == null ? 'skip' : (a === q.ans ? 'ok' : 'bad');
if (S.reviewWrongOnly && state === 'ok') return;
var opts = it.opts.map(function (o, idx) {
var cls = o.k === q.ans ? ' correct' : (o.k === a ? ' wrong' : '');
var mark = o.k === q.ans ? '<span class="mark">✓</span>'
: (o.k === a ? '<span class="mark">✕</span>' : '');
return '<div class="opt' + cls + '">' +
'<span class="key">' + String.fromCharCode(65 + idx) + '</span>' +
'<span class="txt">' + esc(o.t) + codeHTML(o.c) + '</span>' + mark + '</div>';
}).join('');
out.push('<div class="review-item">' +
'<div class="rv-head">' +
'<span class="rv-n">Q' + (i + 1) + '</span>' +
'<span class="rv-tag ' + state + '">' +
(state === 'ok' ? 'Correct' : state === 'bad' ? 'Wrong' : 'Skipped') + '</span>' +
'<span class="badge plain">' + esc(q.topic) + '</span></div>' +
(q.q ? '<p class="qtext" style="font-size:1rem">' + esc(q.q) + '</p>' : '') +
codeHTML(q.code) +
'<div class="opts">' + opts + '</div>' +
'<div class="explain">' +
(q.exp ? '<div class="lbl">Explanation</div><p>' + esc(q.exp) + '</p>' : '') +
(q.expCode ? '<div class="lbl">Output</div>' + codeHTML(q.expCode) : '') +
'<div class="src">Source: <a href="' + esc(q.src) + '" target="_blank" rel="noopener">' +
esc(q.src) + '</a></div></div></div>');
});
$('rsReview').innerHTML = out.join('') ||
'<p class="sub" style="margin:0">Nothing to show.</p>';
}
$('btnFilterAll').onclick = function () { S.reviewWrongOnly = false; renderReview(); };
$('btnFilterWrong').onclick = function () { S.reviewWrongOnly = true; renderReview(); };
$('btnAgain').onclick = function () { show('screenStart'); };
$('btnRetryWrong').onclick = function () {
var wrong = S.list.filter(function (it, i) { return S.answers[i] !== it.q.ans; })
.map(function (it) { return it.q; });
if (wrong.length) startQuiz(wrong);
};
$('btnExport').onclick = function () {
var rows = [['#', 'Category', 'Topic', 'Question', 'Your answer', 'Sanfoundry answer', 'Result', 'Source']];
S.list.forEach(function (it, i) {
var q = it.q, a = S.answers[i];
rows.push([i + 1, q.cat, q.topic, q.q.replace(/\s+/g, ' '),
a ? a.toUpperCase() : '', q.ans.toUpperCase(),
a == null ? 'Skipped' : (a === q.ans ? 'Correct' : 'Wrong'), q.src]);
});
var csv = rows.map(function (r) {
return r.map(function (c) { return '"' + String(c).replace(/"/g, '""') + '"'; }).join(',');
}).join('\r\n');
var blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'java-quiz-results.csv';
a.click();
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
};
$('btnStart').onclick = function () { startQuiz(null); };
/* ---------------- theory tab ---------------- */
var TH = (window.THEORY_DATA || {
items: [], keypoints: [], predicted: [], sources: [], topicsBySource: {}
});
var thSrc = 'All', thTopic = 'All';
function thBySource() {
return thSrc === 'All' ? TH.items
: TH.items.filter(function (x) { return x.src === thSrc; });
}
function thPool() {
return thBySource().filter(function (x) {
return thTopic === 'All' || x.topic === thTopic;
});
}
function thTopicList() {
var seen = [], src = thBySource();
src.forEach(function (x) { if (seen.indexOf(x.topic) < 0) seen.push(x.topic); });
return seen;
}
function partBadge(x) {
if (x.part === 'Likely exam prompts') return '<span class="rv-tag skip">exam prompt</span>';
if (x.part === 'Model questions') return '<span class="rv-tag ok">model answer</span>';
return '';
}
function thRender() {
var list = thPool();
$('thHint').textContent = list.length + ' question' + (list.length === 1 ? '' : 's');
$('thList').innerHTML = list.map(function (f) {
var noAnswer = !f.a && !(f.rich && f.rich.define);
var ref = /^https?:/.test(f.ref)
? '<a href="' + esc(f.ref) + '" target="_blank" rel="noopener">' + esc(f.ref) + '</a>'
: esc(f.ref);
return '<div class="card qcard th">' +
'<div class="qhead">' +
'<span class="badge">' + esc(f.topic) + '</span>' +
'<span class="badge plain">' + esc(f.src) + '</span>' +
partBadge(f) + '</div>' +
'<p class="qtext">' + esc(f.q) + '</p>' +
(noAnswer
? '<div class="th-prompt">No model answer in the source — this is a prompt to ' +
'rehearse. Use <b>Define → Example → Explain</b>.</div>'
: '<button class="btn ghost th-toggle">Show answer</button>' +
'<div class="th-ans hide">' +
(f.rich ? richAnswer(f.rich) : fmtAnswer(f.a)) +
'<div class="src">Source: ' + ref + '</div></div>') +
'</div>';
}).join('') || '<div class="card"><p class="sub" style="margin:0">Nothing here.</p></div>';
var showKeys = (thSrc === 'All' || thSrc === 'Sanfoundry');
var keys = showKeys
? TH.keypoints.filter(function (k) { return thTopic === 'All' || k.topic === thTopic; })
: [];
$('thKeyCard').classList.toggle('hide', !keys.length);
$('thKeys').innerHTML = keys.map(function (k) {
return '<div class="keyblock"><div class="lbl">' + esc(k.topic) + '</div><ul>' +
k.points.map(function (p) { return '<li>' + esc(p) + '</li>'; }).join('') +
'</ul></div>';
}).join('');
}
// COS 202 answers are structured: definition, key points, code, memory hook.
function richAnswer(r) {
var h = '';
if (r.define) {
h += '<div class="ans-def"><span class="ans-lbl">Definition — write this first</span>' +
esc(r.define) + '</div>';
}
if (r.points && r.points.length) {
h += '<div class="ans-lbl">Key points</div><ul class="ans-pts">' +
r.points.map(function (p) { return '<li>' + esc(p) + '</li>'; }).join('') + '</ul>';
}
if (r.code) {
h += '<div class="ans-lbl">Example</div>' + codeHTML([r.code]);
}
if (r.remember) {
h += '<div class="ans-hook"><b>Remember:</b> ' + esc(r.remember) + '</div>';
}
if (r.notes) {
h += '<details class="ans-notes"><summary>Your PDF’s shorter wording</summary>' +
'<p>' + esc(r.notes) + '</p></details>';
}
return h;
}
function fmtAnswer(a) {
var lines = String(a).split('\n');
var out = '', bullets = [];
function flush() {
if (bullets.length) {
out += '<ul>' + bullets.map(function (b) { return '<li>' + esc(b) + '</li>'; }).join('') + '</ul>';
bullets = [];
}
}
lines.forEach(function (l) {
l = l.trim();
if (!l) return;
if (l.indexOf('•') === 0) bullets.push(l.replace(/^•\s*/, ''));
else { flush(); out += '<p>' + esc(l) + '</p>'; }
});
flush();
return out;
}
$('thList').addEventListener('click', function (e) {
var b = e.target.closest ? e.target.closest('.th-toggle') : null;
if (!b) return;
var ans = b.parentNode.querySelector('.th-ans');
var shown = !ans.classList.contains('hide');
ans.classList.toggle('hide', shown);
b.textContent = shown ? 'Show answer' : 'Hide answer';
});
function thSetAll(show) {
Array.prototype.forEach.call(document.querySelectorAll('#thList .th-ans'),
function (a) { a.classList.toggle('hide', !show); });
Array.prototype.forEach.call(document.querySelectorAll('#thList .th-toggle'),
function (b) { b.textContent = show ? 'Hide answer' : 'Show answer'; });
}
$('thReveal').onclick = function () { thSetAll(true); };
$('thHide').onclick = function () { thSetAll(false); };
function chipsInto(el, values, current, onPick, countFn) {
el.innerHTML = '';
values.forEach(function (v) {
var b = document.createElement('button');
b.className = 'chip' + (v === current ? ' on' : '');
b.innerHTML = esc(v) + (countFn ? '<span class="n">' + countFn(v) + '</span>' : '');
b.onclick = function () {
onPick(v);
Array.prototype.forEach.call(el.children, function (x) { x.classList.remove('on'); });
b.classList.add('on');
};
el.appendChild(b);
});
}
function thRenderTopics() {
var list = thTopicList();
if (list.indexOf(thTopic) < 0) thTopic = 'All';
chipsInto($('thChips'), ['All'].concat(list), thTopic,
function (t) { thTopic = t; thRender(); },
function (t) {
return t === 'All' ? thBySource().length
: thBySource().filter(function (x) { return x.topic === t; }).length;
});
}
function thPredicted() {
$('thPredList').innerHTML = TH.predicted.map(function (p, i) {
var opts = p.opts.map(function (o, idx) {
return '<li class="' + (idx === p.ans ? 'right' : '') + '">' +
'<span class="lk">' + String.fromCharCode(97 + idx) + '</span>' +
'<span class="lt">' + esc(o).replace(/\n/g, '<br>') + '</span>' +
(idx === p.ans ? '<span class="tick">✔</span>' : '') + '</li>';
}).join('');
return '<div class="review-item">' +
'<div class="rv-head"><span class="rv-n">P' + (i + 1) + '</span>' +
'<span class="badge plain">' + esc(p.topic) + '</span>' +
'<span class="rv-tag ok">verified by running it</span></div>' +
'<p class="qtext" style="font-size:1rem">What will be the output of the following Java code?</p>' +
codeHTML([p.code]) +
'<ol class="opts th-opts">' + opts + '</ol>' +
'<div class="explain"><div class="lbl">Why</div><p>' + esc(p.why) + '</p></div></div>';
}).join('');
}
function buildTheory() {
var M = TH.meta || {};
$('thCount').textContent = TH.items.length;
$('thCos').textContent = M.cos202 || 0;
$('thPoints').textContent = M.keypointCount || 0;
$('thPred').textContent = TH.predicted.length;
chipsInto($('thSrcChips'), ['All'].concat(TH.sources || []), 'All',
function (s) { thSrc = s; thRenderTopics(); thRender(); },
function (s) {
return s === 'All' ? TH.items.length
: TH.items.filter(function (x) { return x.src === s; }).length;
});
thRenderTopics();
thRender();
thPredicted();
}
/* ---------------- tabs ---------------- */
function setTab(which) {
var theory = which === 'theory';
$('tabQuiz').classList.toggle('on', !theory);
$('tabTheory').classList.toggle('on', theory);
if (theory) {
['screenStart', 'screenQuiz', 'screenResult'].forEach(function (id) {
$(id).classList.add('hide');
});
$('screenTheory').classList.remove('hide');
$('btnQuit').classList.add('hide');
} else {
$('screenTheory').classList.add('hide');
show('screenStart');
}
window.scrollTo(0, 0);
}
$('tabQuiz').onclick = function () { setTab('quiz'); };
$('tabTheory').onclick = function () { setTab('theory'); };
/* ---------------- boot ---------------- */
if (!ALL.length) {
$('screenStart').innerHTML =
'<div class="card"><h1>No questions loaded</h1>' +
'<p class="sub">questions.js is missing or failed to load. Keep index.html, styles.css, ' +
'app.js and questions.js together in the same folder.</p></div>';
} else {
buildStart();
buildTheory();
}
})();