-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp-utils.js
More file actions
207 lines (172 loc) · 5.94 KB
/
app-utils.js
File metadata and controls
207 lines (172 loc) · 5.94 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
(function(global){
'use strict';
const isString = (value) => typeof value === 'string' || value instanceof String;
const trimToEmpty = (value) => (isString(value) ? String(value).trim() : '');
const collapseWhitespace = (value) => trimToEmpty(value).replace(/\s+/g, ' ');
const hasText = (value) => trimToEmpty(value).length > 0;
const formatQuestionPrompt = (question) => {
if (!question || typeof question !== 'object') return '';
const id = trimToEmpty(question.id);
const text = trimToEmpty(question.text);
if (id && text) return `(${id}) ${text}`;
if (id) return `(${id})`;
return text;
};
const getGroupKey = (question) => {
const id = trimToEmpty(question && question.id);
if (id.length < 3) return '';
return id.slice(0, 3).toUpperCase();
};
const buildExamRun = (pool, options = {}) => {
const {
required = 35,
filterFigures = false,
hasFigure = () => false,
rng = Math.random,
} = options;
if (!Array.isArray(pool) || pool.length === 0) {
throw new Error('Question pool is invalid or empty.');
}
const groupOrder = [];
const groupBuckets = new Map();
pool.forEach((question) => {
const group = getGroupKey(question);
if (!group) return;
if (!groupBuckets.has(group)) {
groupBuckets.set(group, []);
groupOrder.push(group);
}
groupBuckets.get(group).push(question);
});
if (groupOrder.length === 0) {
throw new Error('Question pool is missing group identifiers.');
}
if (required > groupOrder.length) {
throw new Error('Question pool does not contain enough groups to build an exam.');
}
const shuffledGroups = [...groupOrder];
for (let i = shuffledGroups.length - 1; i > 0; i -= 1) {
const pick = Math.floor(rng() * (i + 1));
[shuffledGroups[i], shuffledGroups[pick]] = [shuffledGroups[pick], shuffledGroups[i]];
}
const selections = [];
for (let i = 0; i < required; i += 1) {
const group = shuffledGroups[i];
const candidates = groupBuckets.get(group) || [];
const viable = filterFigures ? candidates.filter((q) => !hasFigure(q)) : candidates;
if (viable.length === 0) {
throw new Error(filterFigures ? 'Not enough non-figure questions to build a full exam.' : `Question group ${group} is empty.`);
}
const pickIndex = Math.floor(rng() * viable.length);
selections.push(viable[pickIndex]);
}
return selections;
};
const parsePlainTextPool = (rawText, options = {}) => {
if (!isString(rawText)) {
throw new Error('Question pool source must be a string.');
}
const {
expectedChoices = ['A', 'B', 'C', 'D'],
allowDuplicateIds = false,
normalizeWhitespace = true,
onQuestion = null,
} = options;
const normalizeText = (value) => {
if (!normalizeWhitespace) return trimToEmpty(value);
return collapseWhitespace(value);
};
const lines = rawText.replace(/\r\n?/g, '\n').split('\n');
const questions = [];
const seenIds = new Set();
const isChoiceLine = (line) => /^[A-D]\.\s/.test(line);
const isHeaderLine = (line) => /^[A-Za-z][A-Za-z0-9]{2,5}\s*\([A-D]\)/.test(line);
for (let index = 0; index < lines.length; index += 1) {
const headerCandidate = trimToEmpty(lines[index]);
const headerMatch = headerCandidate.match(/^([A-Za-z][A-Za-z0-9]{2,5})\s*\(([A-D])\)\s*(?:\[(.*?)\])?$/);
if (!headerMatch) continue;
const id = headerMatch[1].toUpperCase();
const correct = headerMatch[2].toUpperCase();
const reference = trimToEmpty(headerMatch[3]);
index += 1;
const questionParts = [];
while (index < lines.length) {
const rawLine = lines[index];
const trimmed = trimToEmpty(rawLine);
if (!trimmed) {
index += 1;
continue;
}
if (trimmed === '~~' || isChoiceLine(trimmed) || isHeaderLine(trimmed)) break;
questionParts.push(rawLine);
index += 1;
}
const questionText = normalizeText(questionParts.join(' '));
const choices = {};
let currentLetter = '';
while (index < lines.length) {
const rawLine = lines[index];
const trimmed = trimToEmpty(rawLine);
if (!trimmed) {
index += 1;
continue;
}
if (trimmed === '~~') {
index += 1;
break;
}
if (isHeaderLine(trimmed)) break;
const choiceMatch = trimmed.match(/^([A-D])\.\s*(.*)$/);
if (choiceMatch) {
currentLetter = choiceMatch[1].toUpperCase();
choices[currentLetter] = normalizeText(choiceMatch[2]);
index += 1;
continue;
}
if (currentLetter) {
const existing = choices[currentLetter] || '';
choices[currentLetter] = normalizeText(`${existing} ${rawLine}`);
index += 1;
continue;
}
questionParts.push(rawLine);
index += 1;
}
const hasAllChoices = expectedChoices.every((letter) => hasText(choices[letter]));
if (!hasAllChoices) {
continue;
}
if (!allowDuplicateIds) {
if (seenIds.has(id)) continue;
seenIds.add(id);
}
const question = {
id,
text: questionText,
choices,
correct,
};
if (reference) question.reference = reference;
questions.push(question);
if (typeof onQuestion === 'function') {
onQuestion(question);
}
}
return questions;
};
const escapeHTML = (value) => String(value || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
const api = {
formatQuestionPrompt,
buildExamRun,
parsePlainTextPool,
escapeHTML,
};
global.HAMLEARN_UTILS = api;
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
}
})(typeof window !== 'undefined' ? window : globalThis);