-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.js
More file actions
885 lines (776 loc) · 26.9 KB
/
Copy pathcore.js
File metadata and controls
885 lines (776 loc) · 26.9 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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
// core.js
(function () {
const NEET_SUBJECT_WEIGHTS = {
"Anatomy": 9.714,
"Physiology": 8.000,
"Biochemistry": 10.571,
"Microbiology": 12.857,
"Pathology": 15.714,
"Pharmacology": 13.429,
"Forensic Medicine": 8.571,
"Social & Preventive Medicine": 18.143,
"Ophthalmology": 8.857,
"ENT": 7.429,
"General Medicine": 16.286,
"General Surgery": 16.429,
"Gynaecology & Obstetrics": 15.143,
"Pediatrics": 9.857,
"Anaesthesiology": 4.286,
"Dermatology": 6.143,
"Psychiatry": 5.571,
"Orthopaedics": 7.000,
"Radiodiagnosis": 6.000
};
const STORAGE_KEY = "medmcqa_trainer_state_v6";
const DEFAULT_DECK = "Bookmarks";
const DB_NAME = "MedMCQA_Trainer_DB";
const STORE_NAME = "mcqa_data";
/**
* Main Core object handling state management, data parsing, caching,
* and complex filtering/selection logic.
*/
const Core = {
state: {
questions: [],
questionById: {},
subjectsAll: new Set(),
subjectsActive: new Set(),
subjectNoneActive: false,
filters: {
selectionMode: "smart", // smart | new | shuffle
status: "any", // any | unanswered | answered | weak | hard
pool: "deck", // deck | playlist
},
appState: {
version: 2,
stats: {},
playlists: { decks: {}, activeDeck: DEFAULT_DECK },
lastDeck: null,
currentQuestionId: null,
examUseWeights: true,
}
},
// ------ basic accessors ------
get stats() {
return this.state.appState.stats;
},
get playlists() {
return this.state.appState.playlists;
},
init() {
this.loadAppState();
this.ensurePlaylistsShape();
},
// ------ IndexedDB for caching large JSON data ------
initDB() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = (e) => {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
request.onsuccess = (e) => resolve(e.target.result);
request.onerror = (e) => reject(e.target.error);
});
},
async saveQuestionsToDB(rawText, filename) {
try {
const db = await this.initDB();
const tx = db.transaction(STORE_NAME, "readwrite");
const store = tx.objectStore(STORE_NAME);
store.put({ rawText, filename }, "cached_dataset");
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
} catch (e) {
console.error("Failed to save to IndexedDB:", e);
}
},
async loadQuestionsFromDB() {
try {
const db = await this.initDB();
const tx = db.transaction(STORE_NAME, "readonly");
const store = tx.objectStore(STORE_NAME);
const req = store.get("cached_dataset");
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
} catch (e) {
console.error("Failed to load from IndexedDB:", e);
return null;
}
},
async clearDB() {
try {
const db = await this.initDB();
const tx = db.transaction(STORE_NAME, "readwrite");
const store = tx.objectStore(STORE_NAME);
store.delete("cached_dataset");
} catch (e) {
console.error("Failed to clear DB:", e);
}
},
// ------ storage ------
loadAppState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed === "object") {
this.state.appState = parsed;
}
}
} catch (e) {
console.error("Failed to load appState:", e);
}
if (!this.state.appState.stats) this.state.appState.stats = {};
if (!this.state.appState.playlists) {
this.state.appState.playlists = { decks: {}, activeDeck: DEFAULT_DECK };
}
if (typeof this.state.appState.examUseWeights !== "boolean") {
this.state.appState.examUseWeights = true; // default
}
this.ensurePlaylistsShape();
},
saveAppState() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(this.state.appState));
} catch (e) {
console.error("Failed to save appState:", e);
}
},
resetProgress() {
this.state.appState.stats = {};
this.state.appState.playlists = { decks: {}, activeDeck: DEFAULT_DECK };
this.state.appState.lastDeck = null;
this.state.appState.currentQuestionId = null;
this.state.appState.examUseWeights = true; // reset to default
this.ensurePlaylistsShape();
this.saveAppState();
},
async hardReset() {
this.resetProgress();
await this.clearDB();
this.state.questions = [];
this.state.questionById = {};
this.state.subjectsAll = new Set();
this.state.subjectsActive = new Set();
this.state.subjectNoneActive = false;
},
ensurePlaylistsShape() {
const pl = this.state.appState.playlists;
if (!pl.decks) pl.decks = {};
if (!pl.activeDeck) pl.activeDeck = DEFAULT_DECK;
if (!pl.decks[DEFAULT_DECK]) {
pl.decks[DEFAULT_DECK] = { name: DEFAULT_DECK, ids: [] };
}
},
// ------ MedMCQA parsing & loading ------
/**
* Normalizes a myriad of subject strings into the standardized NEET subject buckets
* defined in NEET_SUBJECT_WEIGHTS.
* @param {string} subj - The raw subject string from MedMCQA.
* @returns {string} Normalized subject name.
*/
normalizeSubjectName(subj) {
if (!subj) return "Other";
const original = String(subj).trim();
let s = original.toLowerCase();
if (s.includes("preventive") || s.includes("community") || s.includes("social & preventive")) {
return "Social & Preventive Medicine";
}
if (s.includes("gyn") || s.includes("obstet") || s.includes("obg")) {
return "Gynaecology & Obstetrics";
}
if (s.includes("dermat") || s.includes("skin")) {
return "Dermatology";
}
if (s.includes("radio")) return "Radiodiagnosis";
if (s.includes("anaesth") || s.includes("anesth")) return "Anaesthesiology";
if (s.includes("otorhino") || s === "ent") return "ENT";
if (s.includes("ophthal")) return "Ophthalmology";
if (s.includes("pediatr") || s.includes("paediatr")) return "Pediatrics";
if (s.includes("ortho")) return "Orthopaedics";
if (s.includes("psychiat")) return "Psychiatry";
if (s.includes("forensic")) return "Forensic Medicine";
if (s.includes("pathol")) return "Pathology";
if (s.includes("pharm")) return "Pharmacology";
if (s.includes("microbio")) return "Microbiology";
if (s.includes("biochem")) return "Biochemistry";
if (s.includes("physiol")) return "Physiology";
if (s.includes("anatom")) return "Anatomy";
if (s.includes("medicine")) return "General Medicine";
if (s.includes("surgery")) return "General Surgery";
return original;
},
normalizeMedmcqaQuestion(item, index) {
if (!item) return null;
const id = item.id || `q_${index + 1}`;
const question = item.question;
const options = [
item.opa,
item.opb,
item.opc,
item.opd,
].filter(o => o !== null && o !== undefined);
let correctIndex = null;
const cop = item.cop;
if (typeof cop === "number") correctIndex = cop - 1;
else if (typeof cop === "string") {
const n = Number(cop.trim());
if (!Number.isNaN(n)) correctIndex = n - 1;
}
if (!question || options.length < 2 || correctIndex == null ||
correctIndex < 0 || correctIndex >= options.length) {
return null;
}
const explanation = item.exp || "";
const rawSubject = item.subject_name || "";
const subject = this.normalizeSubjectName(rawSubject);
const topic = item.topic_name || "";
const choiceType = item.choice_type || "";
return {
id: String(id),
question: String(question),
options: options.map(o => (typeof o === "string" ? o : JSON.stringify(o))),
correctIndex,
explanation: String(explanation || ""),
subject,
topic,
choiceType,
_raw: item
};
},
parseMedmcqa(raw) {
let arr = null;
if (Array.isArray(raw)) {
arr = raw;
} else if (raw && typeof raw === "object") {
if (Array.isArray(raw.data)) arr = raw.data;
else if (Array.isArray(raw.train)) arr = raw.train;
else if (Array.isArray(raw.dev)) arr = raw.dev;
else if (Array.isArray(raw.test)) arr = raw.test;
} else if (typeof raw === "string") {
const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(l => l.length > 0);
const objs = [];
for (let i = 0; i < lines.length; i++) {
try {
objs.push(JSON.parse(lines[i]));
} catch (e) {
console.warn("Skipping invalid JSON line", i + 1, e);
}
}
arr = objs;
}
if (!Array.isArray(arr)) return [];
const normalized = arr.map((item, idx) =>
this.normalizeMedmcqaQuestion(item, idx)
).filter(Boolean);
return normalized;
},
loadQuestionsFromText(text, filename) {
let raw;
try {
raw = JSON.parse(text);
} catch (e) {
raw = text;
}
const questions = this.parseMedmcqa(raw);
this.state.questions = questions;
this.state.questionById = {};
this.state.subjectsAll = new Set();
this.state.subjectsActive = new Set();
const subjectCounts = {};
for (const q of questions) {
this.state.questionById[q.id] = q;
const subj = q.subject || "Other";
this.state.subjectsAll.add(subj);
subjectCounts[subj] = (subjectCounts[subj] || 0) + 1;
}
this.state.subjectsActive = new Set(this.state.subjectsAll);
this.state.subjectNoneActive = false;
this.state.appState.lastDeck = {
filename,
questionCount: questions.length,
subjects: subjectCounts
};
this.saveAppState();
// Async save to indexedDB so it isn't blocking the UI
this.saveQuestionsToDB(text, filename);
return {
total: questions.length,
subjects: subjectCounts
};
},
// ------ stats & difficulty ------
getStatsFor(id) {
return this.stats[id] || null;
},
ensureStat(id) {
if (!this.stats[id]) {
const now = Date.now();
this.stats[id] = {
totalAttempts: 0,
correctAttempts: 0,
lastResult: null,
firstSeenAt: now,
lastSeenAt: null
};
}
return this.stats[id];
},
updateStatsForAnswer(id, isCorrect) {
const now = Date.now();
const s = this.ensureStat(id);
s.totalAttempts += 1;
if (isCorrect) s.correctAttempts += 1;
s.lastResult = isCorrect ? "correct" : "incorrect";
if (!s.firstSeenAt) s.firstSeenAt = now;
s.lastSeenAt = now;
this.saveAppState();
return s;
},
getDifficultyBucket(stat) {
if (!stat || stat.totalAttempts === 0) return "Unseen";
const acc = stat.correctAttempts / stat.totalAttempts;
if (acc <= 0.4) return "Hard";
if (acc <= 0.7) return "Medium";
return "Easy";
},
isWeak(stat) {
if (!stat || stat.totalAttempts === 0) return false;
const acc = stat.correctAttempts / stat.totalAttempts;
return acc < 0.6;
},
isHard(stat) {
if (!stat || stat.totalAttempts === 0) return false;
const acc = stat.correctAttempts / stat.totalAttempts;
return acc <= 0.4;
},
getGlobalStatsSummary() {
const total = this.state.questions.length;
let attemptedCount = 0;
let totalAttempts = 0;
let correctAttempts = 0;
for (const q of this.state.questions) {
const s = this.stats[q.id];
if (s && s.totalAttempts > 0) {
attemptedCount++;
totalAttempts += s.totalAttempts;
correctAttempts += s.correctAttempts;
}
}
let accuracyPct = null;
if (totalAttempts > 0) {
accuracyPct = Math.round((correctAttempts / totalAttempts) * 100);
}
return {
totalQuestions: total,
attemptedCount,
totalAttempts,
correctAttempts,
accuracyPct
};
},
getProgressSummary() {
let attemptedCount = 0;
let masteredCount = 0;
for (const q of this.state.questions) {
const s = this.stats[q.id];
if (s && s.totalAttempts > 0) {
attemptedCount++;
if (s.correctAttempts >= 3) masteredCount++;
}
}
return {
total: this.state.questions.length,
attemptedCount,
masteredCount
};
},
// ------ subject filters ------
getAllSubjectsArray() {
return Array.from(this.state.subjectsAll).sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase())
);
},
setSubjectActive(subject, active) {
if (active) {
this.state.subjectNoneActive = false;
this.state.subjectsActive.add(subject);
} else {
this.state.subjectsActive.delete(subject);
}
},
resetSubjectFiltersToAll() {
this.state.subjectNoneActive = false;
this.state.subjectsActive = new Set(this.state.subjectsAll);
},
subjectFilterAllows(q) {
// Explicit "None" → block all questions by subject
if (this.state.subjectNoneActive) return false;
// If we don't know subjects yet, don't restrict
if (this.state.subjectsAll.size === 0) return true;
// Empty active set (but not "None") = no restriction
if (this.state.subjectsActive.size === 0) return true;
const subj = q.subject || "Other";
return this.state.subjectsActive.has(subj);
},
setSubjectNoneActive(active) {
this.state.subjectNoneActive = !!active;
if (this.state.subjectNoneActive) {
// "None" explicitly excludes everything; we can clear active set
this.state.subjectsActive = new Set();
} else if (this.state.subjectsActive.size === 0 && this.state.subjectsAll.size > 0) {
// If leaving "None" and no explicit subset chosen,
// default back to "All" to keep UX sane
this.resetSubjectFiltersToAll();
}
},
isSubjectNoneActive() {
return this.state.subjectNoneActive;
},
// ------ status filter ------
setStatusFilter(mode) {
this.state.filters.status = mode;
},
statusFilterAllows(q) {
const s = this.stats[q.id];
switch (this.state.filters.status) {
case "unanswered":
return !s || s.totalAttempts === 0;
case "answered":
return s && s.totalAttempts > 0;
case "weak":
return this.isWeak(s);
case "hard":
return this.isHard(s);
case "any":
default:
return true;
}
},
// ------ pool filters ------
setPoolSource(pool) {
this.state.filters.pool = pool; // deck | playlist
},
setSelectionMode(mode) {
this.state.filters.selectionMode = mode;
},
setActiveDeckName(name) {
this.ensureDeck(name);
this.playlists.activeDeck = name;
this.saveAppState();
},
getActiveDeckName() {
this.ensureDeck(this.playlists.activeDeck);
return this.playlists.activeDeck;
},
// ------ decks / playlists ------
ensureDeck(name) {
if (!name) return;
if (!this.playlists.decks[name]) {
this.playlists.decks[name] = { name, ids: [] };
}
},
getDeck(name) {
this.ensureDeck(name);
return this.playlists.decks[name];
},
getAllDecks() {
const decks = this.playlists.decks || {};
return Object.keys(decks).sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase())
).map(name => decks[name]);
},
isInDeck(deckName, id) {
const deck = this.getDeck(deckName);
return deck.ids.includes(id);
},
addToDeck(deckName, id) {
const deck = this.getDeck(deckName);
if (!deck.ids.includes(id)) deck.ids.push(id);
this.saveAppState();
},
removeFromDeck(deckName, id) {
const deck = this.getDeck(deckName);
const idx = deck.ids.indexOf(id);
if (idx !== -1) deck.ids.splice(idx, 1);
this.saveAppState();
},
isBookmarked(id) {
return this.isInDeck(DEFAULT_DECK, id);
},
toggleBookmark(id) {
if (this.isBookmarked(id)) {
this.removeFromDeck(DEFAULT_DECK, id);
} else {
this.addToDeck(DEFAULT_DECK, id);
}
},
// ------ filtered pool & selection ------
poolSourceAllows(q) {
if (this.state.filters.pool === "deck") return true;
if (this.state.filters.pool === "playlist") {
const activeName = this.getActiveDeckName();
const deck = this.getDeck(activeName);
const set = new Set(deck.ids);
return set.has(q.id);
}
return true;
},
getFilteredPool() {
let base = this.state.questions;
if (this.state.filters.pool === "playlist") {
const activeName = this.getActiveDeckName();
const deck = this.getDeck(activeName);
const set = new Set(deck.ids);
base = this.state.questions.filter(q => set.has(q.id));
}
// Apply subject + status filters directly.
// If nothing matches, we return [] (no fallback).
const pool = base.filter(q =>
this.subjectFilterAllows(q) && this.statusFilterAllows(q)
);
return pool;
},
pickFromPool(pool) {
if (!pool || pool.length === 0) return null;
const mode = this.state.filters.selectionMode;
if (mode === "shuffle") {
return pool[Math.floor(Math.random() * pool.length)];
}
const unseen = [];
const weak = [];
const others = [];
for (const q of pool) {
const s = this.stats[q.id];
if (!s || s.totalAttempts === 0) unseen.push(q);
else if (this.isWeak(s)) weak.push(q);
else others.push(q);
}
if (mode === "new") {
if (unseen.length > 0) {
return unseen[Math.floor(Math.random() * unseen.length)];
}
return pool[Math.floor(Math.random() * pool.length)];
}
if (unseen.length > 0) {
return unseen[Math.floor(Math.random() * unseen.length)];
}
if (weak.length > 0) {
return weak[Math.floor(Math.random() * weak.length)];
}
return pool[Math.floor(Math.random() * pool.length)];
},
// ------ Weighted exam subset (with jitter) + distribution helper ------
/**
* Builds a mock exam subset of questions mimicking NEET PG distributions.
* Uses NEET_SUBJECT_WEIGHTS to pick a proportional number of questions per subject.
*
* @param {number} totalQuestions - Target number of questions (e.g., 200).
* @param {boolean} useWeights - Whether to apply NEET subject weights.
* @param {number} jitterFraction - Adds randomness to the exact question counts
* per subject so exams aren't identical every time.
* @returns {Array|null} Array of question objects representing the exam pool.
*/
buildExamSubset(totalQuestions, useWeights = true, jitterFraction = 0.15) {
// Base pool: respect subject filters, ignore status for exam
const basePool = this.state.questions.filter(q => this.subjectFilterAllows(q));
if (basePool.length === 0) return null;
const requiredTotal = Math.min(totalQuestions, basePool.length);
const weightsMap = this.getExamWeights();
if (!useWeights || !weightsMap) {
// Uniform random
const shuffled = basePool.slice().sort(() => Math.random() - 0.5);
return shuffled.slice(0, requiredTotal);
}
// Group questions by subject
const bySubject = {};
for (const q of basePool) {
const subj = q.subject || "Other";
if (!bySubject[subj]) bySubject[subj] = [];
bySubject[subj].push(q);
}
// Build jittered weights for subjects present in this deck
const entries = [];
for (const [subj, qs] of Object.entries(bySubject)) {
const baseW = weightsMap[subj] != null ? weightsMap[subj] : 1;
if (baseW <= 0 || qs.length === 0) continue;
const r = (Math.random() * 2 - 1) * jitterFraction; // [-jitter, +jitter]
const jittered = Math.max(0.01, baseW * (1 + r));
entries.push([subj, jittered]);
}
if (entries.length === 0) {
const shuffled = basePool.slice().sort(() => Math.random() - 0.5);
return shuffled.slice(0, requiredTotal);
}
// Shuffle questions within each subject once
const shuffledBySubject = {};
for (const [subj] of entries) {
const arr = bySubject[subj].slice();
arr.sort(() => Math.random() - 0.5);
shuffledBySubject[subj] = arr;
}
const totalWeight = entries.reduce((sum, [, w]) => sum + w, 0);
const allocations = entries.map(([subj, w]) => {
const ideal = (w / totalWeight) * requiredTotal;
const floor = Math.floor(ideal);
const frac = ideal - floor;
return {
subj,
ideal,
floor,
frac,
used: 0,
capacity: shuffledBySubject[subj].length
};
});
let subset = [];
let allocated = 0;
// 1) Give everyone their floored share
for (const a of allocations) {
const want = Math.min(a.floor, a.capacity);
if (want > 0) {
subset.push(...shuffledBySubject[a.subj].slice(0, want));
a.used = want;
allocated += want;
}
}
// 2) Distribute remaining based on fractional part
let remaining = requiredTotal - allocated;
allocations.sort((a, b) => b.frac - a.frac);
while (remaining > 0) {
let progress = false;
for (const a of allocations) {
if (remaining <= 0) break;
if (a.used < a.capacity) {
subset.push(shuffledBySubject[a.subj][a.used]);
a.used += 1;
remaining -= 1;
progress = true;
}
}
if (!progress) break;
}
// 3) Top up from leftovers if still short
if (subset.length < requiredTotal) {
const usedIds = new Set(subset.map(q => q.id));
const leftovers = basePool.filter(q => !usedIds.has(q.id));
leftovers.sort(() => Math.random() - 0.5);
const need = requiredTotal - subset.length;
subset.push(...leftovers.slice(0, need));
}
if (subset.length > requiredTotal) {
subset = subset.slice(0, requiredTotal);
}
return subset;
},
getExamDistributionForQuestions(questions, totalQuestions) {
const weights = this.getExamWeights();
const counts = {};
for (const q of questions) {
const subj = q.subject || "Other";
counts[subj] = (counts[subj] || 0) + 1;
}
// Only consider subjects actually present in this exam
const subjects = Object.keys(counts).sort((a, b) =>
a.toLowerCase().localeCompare(b.toLowerCase())
);
// Sum weights only for these subjects
let totalWeight = 0;
subjects.forEach(subj => {
const w = weights[subj];
if (w && w > 0) totalWeight += w;
});
const rows = subjects.map(subj => {
const actual = counts[subj];
let target = null;
const w = weights[subj];
if (w && totalWeight > 0) {
target = Math.round((w / totalWeight) * totalQuestions);
}
return { subject: subj, actual, target };
});
return rows;
},
// ------ per-deck stats for summary ------
getDeckSummary(deck) {
const ids = deck.ids || [];
let seen = 0;
let weak = 0;
let totalAttempts = 0;
let correctAttempts = 0;
for (const id of ids) {
const s = this.stats[id];
if (s && s.totalAttempts > 0) {
seen++;
totalAttempts += s.totalAttempts;
correctAttempts += s.correctAttempts;
if (this.isWeak(s)) weak++;
}
}
let accuracyPct = null;
if (totalAttempts > 0) {
accuracyPct = Math.round((correctAttempts / totalAttempts) * 100);
}
return {
name: deck.name,
size: ids.length,
seen,
weak,
accuracyPct
};
},
getAllDeckSummaries() {
return this.getAllDecks().map(deck => this.getDeckSummary(deck));
},
// ------ exam weight helpers ------
getExamWeights() {
return NEET_SUBJECT_WEIGHTS;
},
getExamUseWeights() {
return !!this.state.appState.examUseWeights;
},
setExamUseWeights(flag) {
this.state.appState.examUseWeights = !!flag;
this.saveAppState();
},
// ------ export helpers ------
toMedmcqaRecord(q) {
if (q._raw && typeof q._raw === "object") {
return q._raw;
}
return {
id: q.id,
question: q.question,
opa: q.options[0] ?? "",
opb: q.options[1] ?? "",
opc: q.options[2] ?? "",
opd: q.options[3] ?? "",
cop: (q.correctIndex ?? 0) + 1,
exp: q.explanation || "",
subject_name: q.subject || "",
topic_name: q.topic || "",
choice_type: q.choiceType || "single"
};
},
exportQuestionsAsNDJSON(questions, baseName) {
if (!questions || questions.length === 0) return null;
const recs = questions.map(q => this.toMedmcqaRecord(q));
const lines = recs.map(r => JSON.stringify(r));
const text = lines.join("\n");
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
const filename = `${baseName}_${y}${m}${d}.json`;
return { text, filename };
}
};
window.Core = Core;
})();