SPB Git

Repository Public

quiz.ts 7.2 KB 158 lines typescript

1/**2 * Exercise engine: pure grading logic for every question type. No DOM, no storage.3 * Quizzes are formative: answer keys travel to the browser by design, and the UI says so.4 */5import type { Question, Quiz } from "../content-schema/schema";6import { fold } from "./text";78export type Answer =9  | { type: "single"; value: string | null }10  | { type: "multiple"; value: string[] }11  | { type: "true-false"; value: boolean | null }12  | { type: "ordering"; value: string[] }13  | { type: "matching"; value: Record<string, string> }14  | { type: "numeric"; value: string }15  | { type: "fill-blank"; value: Record<string, string> }16  | { type: "debug"; value: { line: number | null; fix: string | null } }17  | { type: "reflection"; value: { text: string; checks: boolean[] } };1819export interface Grade {20  /** null for self-assessed questions (reflection): the engine does not pretend to grade free text. */21  correct: boolean | null;22  /** Partial credit between 0 and 1. */23  score: number;24  /** Per-part correctness, for precise feedback (blank key, left id, position, option id…). */25  parts: Record<string, boolean>;26}2728/** « 0,20 », « 0.2 », « 1/5 », « −3 », « 1 250,5 » → number. Returns null when it is not a number. */29export function parseNumber(raw: string): number | null {30  const s = raw.replace(/[\s  ]/g, "").replace(/[−–]/g, "-").replace(",", ".");31  if (!s) return null;32  const frac = /^(-?\d+(?:\.\d+)?)\/(\d+(?:\.\d+)?)$/.exec(s);33  if (frac) { const d = Number(frac[2]); return d === 0 ? null : Number(frac[1]) / d; }34  if (!/^-?(\d+\.?\d*|\.\d+)$/.test(s)) return null;35  const n = Number(s);36  return Number.isFinite(n) ? n : null;37}3839export function emptyAnswer(q: Question): Answer {40  switch (q.type) {41    case "single": return { type: "single", value: null };42    case "multiple": return { type: "multiple", value: [] };43    case "true-false": return { type: "true-false", value: null };44    case "ordering": return { type: "ordering", value: q.items.map((i) => i.id) };45    case "matching": return { type: "matching", value: {} };46    case "numeric": return { type: "numeric", value: "" };47    case "fill-blank": return { type: "fill-blank", value: {} };48    case "debug": return { type: "debug", value: { line: null, fix: null } };49    case "reflection": return { type: "reflection", value: { text: "", checks: q.criteria.map(() => false) } };50  }51}5253/** Whether the learner has given enough to be graded. */54export function isAnswered(q: Question, a: Answer): boolean {55  if (a.type !== q.type) return false;56  switch (a.type) {57    case "single": return a.value !== null;58    case "multiple": return a.value.length > 0;59    case "true-false": return a.value !== null;60    case "ordering": return true;61    case "matching": return q.type === "matching" && q.left.every((l) => a.value[l.id]);62    case "numeric": return parseNumber(a.value) !== null;63    case "fill-blank": return q.type === "fill-blank" && Object.keys(q.blanks).every((k) => (a.value[k] ?? "").trim() !== "");64    case "debug": return a.value.line !== null && a.value.fix !== null;65    case "reflection": return a.value.text.trim().length > 0;66  }67}6869const ratio = (parts: Record<string, boolean>) => {70  const v = Object.values(parts);71  return v.length ? v.filter(Boolean).length / v.length : 0;72};73const all = (parts: Record<string, boolean>): Grade => ({ correct: Object.values(parts).every(Boolean), score: ratio(parts), parts });7475export function grade(q: Question, a: Answer): Grade {76  if (a.type !== q.type) return { correct: false, score: 0, parts: {} };77  switch (q.type) {78    case "single": {79      const ok = (a as Extract<Answer, { type: "single" }>).value === q.answer;80      return { correct: ok, score: ok ? 1 : 0, parts: {} };81    }82    case "true-false": {83      const ok = (a as Extract<Answer, { type: "true-false" }>).value === q.answer;84      return { correct: ok, score: ok ? 1 : 0, parts: {} };85    }86    case "multiple": {87      const chosen = new Set((a as Extract<Answer, { type: "multiple" }>).value), wanted = new Set(q.answers);88      const parts: Record<string, boolean> = {};89      for (const o of q.options) parts[o.id] = chosen.has(o.id) === wanted.has(o.id);90      const hits = q.answers.filter((id) => chosen.has(id)).length, wrong = [...chosen].filter((id) => !wanted.has(id)).length;91      return { correct: Object.values(parts).every(Boolean), score: Math.max(0, (hits - wrong) / q.answers.length), parts };92    }93    case "ordering": {94      const value = (a as Extract<Answer, { type: "ordering" }>).value;95      const parts: Record<string, boolean> = {};96      q.order.forEach((id, i) => { parts[id] = value[i] === id; });97      return all(parts);98    }99    case "matching": {100      const value = (a as Extract<Answer, { type: "matching" }>).value;101      const parts: Record<string, boolean> = {};102      for (const l of q.left) parts[l.id] = value[l.id] === q.pairs[l.id];103      return all(parts);104    }105    case "numeric": {106      const n = parseNumber((a as Extract<Answer, { type: "numeric" }>).value);107      // A tiny epsilon absorbs binary rounding (0.1 + 0.2), nothing more.108      const ok = n !== null && Math.abs(n - q.answer) <= q.tolerance + 1e-9;109      return { correct: ok, score: ok ? 1 : 0, parts: {} };110    }111    case "fill-blank": {112      const value = (a as Extract<Answer, { type: "fill-blank" }>).value;113      const parts: Record<string, boolean> = {};114      for (const [key, accepted] of Object.entries(q.blanks)) parts[key] = accepted.some((x) => fold(x) === fold(value[key] ?? ""));115      return all(parts);116    }117    case "debug": {118      const value = (a as Extract<Answer, { type: "debug" }>).value;119      return all({ line: value.line === q.faultyLine, fix: value.fix === q.fix });120    }121    case "reflection":122      return { correct: null, score: 0, parts: {} };123  }124}125126export interface QuizResult {127  /** Points earned on auto-graded questions (partial credit included, rounded to 2 decimals). */128  score: number;129  /** Number of auto-graded questions. */130  total: number;131  correct: number;132  selfAssessed: number;133  passed: boolean | null;134  grades: Record<string, Grade>;135}136137export function gradeQuiz(quiz: Quiz, answers: Record<string, Answer>): QuizResult {138  const grades: Record<string, Grade> = {};139  let score = 0, total = 0, correct = 0, selfAssessed = 0;140  for (const q of quiz.questions) {141    const g = grade(q, answers[q.id] ?? emptyAnswer(q));142    grades[q.id] = g;143    if (g.correct === null) { selfAssessed++; continue; }144    total++; score += g.score; if (g.correct) correct++;145  }146  score = Math.round(score * 100) / 100;147  return { score, total, correct, selfAssessed, passed: quiz.passingScore === undefined ? null : correct >= quiz.passingScore, grades };148}149150/** Deterministic shuffle (mulberry32 + Fisher–Yates) so a retry can reorder options without Math.random in render. */151export function shuffle<T>(items: readonly T[], seed: number): T[] {152  let t = seed >>> 0;153  const rnd = () => { t += 0x6d2b79f5; let r = Math.imul(t ^ (t >>> 15), 1 | t); r ^= r + Math.imul(r ^ (r >>> 7), 61 | r); return ((r ^ (r >>> 14)) >>> 0) / 4294967296; };154  const out = [...items];155  for (let i = out.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [out[i], out[j]] = [out[j]!, out[i]!]; }156  return out;157}158
Files main
Menu

Theme