diff --git a/.github/workflows/practice-verification.yml b/.github/workflows/practice-verification.yml index ae2449d8..758d16d8 100644 --- a/.github/workflows/practice-verification.yml +++ b/.github/workflows/practice-verification.yml @@ -79,6 +79,8 @@ jobs: run: npm run check - name: Check imports run: npm run lint:imports + - name: Check escaped LaTeX strings + run: npm run lint:escaped-latex - name: Check formatting run: npm run format:check - name: Check verification documentation diff --git a/package.json b/package.json index 47d8b740..7811c815 100644 --- a/package.json +++ b/package.json @@ -12,6 +12,7 @@ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "lint:imports": "biome check --only=organizeImports .", + "lint:escaped-latex": "node scripts/lint-escaped-latex.mjs", "lint:verification-docs": "node scripts/lint-verification-docs.mjs", "format:imports": "biome check --write --only=organizeImports .", "format": "prettier --write .", @@ -79,9 +80,10 @@ } }, "lint-staged": { - "*.{js,ts,svelte}": [ + "*.{js,mjs,cjs,mts,cts,jsx,ts,tsx,svelte}": [ "biome check --write --no-errors-on-unmatched", - "prettier --write" + "prettier --write", + "node scripts/lint-escaped-latex.mjs" ], "*.{json,json5,jsonc,css,md,yaml,yml,html,svg}": [ "prettier --write" diff --git a/scripts/lint-escaped-latex.mjs b/scripts/lint-escaped-latex.mjs new file mode 100644 index 00000000..2704ea55 --- /dev/null +++ b/scripts/lint-escaped-latex.mjs @@ -0,0 +1,632 @@ +#!/usr/bin/env node +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import process from "node:process"; +import { pathToFileURL } from "node:url"; +import { parse as parseSvelte } from "svelte/compiler"; +import * as ts from "typescript"; + +/** + * @typedef {object} EscapedLatexViolation + * @property {number} line Source line containing the escaped LaTeX command. + * @property {string} command LaTeX command that uses JavaScript escaping. + * @property {number} offset Source offset of the command. + */ + +/** + * @typedef {object} FileViolation + * @property {string} file Path relative to the project root. + * @property {number} line Source line containing the escaped LaTeX command. + * @property {string} command LaTeX command that uses JavaScript escaping. + */ + +const DEFAULT_TARGETS = ["src", "tests", "scripts"]; +const SUPPORTED_EXTENSIONS = new Set([ + ".cjs", + ".cts", + ".js", + ".jsx", + ".mjs", + ".mts", + ".svelte", + ".ts", + ".tsx", +]); +const LATEX_COMMANDS = new Set([ + "alpha", + "angle", + "approx", + "arg", + "begin", + "beta", + "mathbf", + "cdot", + "circ", + "cos", + "deg", + "delta", + "Delta", + "dfrac", + "displaystyle", + "dots", + "end", + "equiv", + "epsilon", + "eta", + "exp", + "F", + "frac", + "Gamma", + "gamma", + "ge", + "iff", + "implies", + "in", + "infty", + "int", + "j", + "le", + "left", + "leftrightarrow", + "lim", + "ln", + "log", + "Lambda", + "lambda", + "longleftrightarrow", + "Longrightarrow", + "mathbb", + "mathcal", + "mathrm", + "max", + "min", + "mp", + "mu", + "ne", + "neq", + "omega", + "Omega", + "operatorname", + "phi", + "pi", + "pm", + "pmod", + "Phi", + "Psi", + "qquad", + "quad", + "Re", + "right", + "rm", + "sigma", + "Sigma", + "sin", + "sqrt", + "square", + "prod", + "sum", + "tan", + "tau", + "text", + "textasciicircum", + "texttt", + "tfrac", + "Theta", + "theta", + "tilde", + "times", + "to", + "X", +]); +const ESCAPED_CONTROL_SEQUENCE = /(?:\\\\)+([A-Za-z]+)/g; + +/** + * Finds escaped LaTeX commands in JavaScript, TypeScript, or Svelte source. + * + * @param {string} source Source contents to inspect. + * @param {string} filePath File path used to select the parser. + * @returns {EscapedLatexViolation[]} Escaped LaTeX commands found in the source. + */ +export function findEscapedLatexViolations(source, filePath) { + /** @type {EscapedLatexViolation[]} */ + const violations = []; + + if (path.extname(filePath) === ".svelte") { + scanSvelteSource(source, filePath, violations); + } else { + scanTypeScriptSource(source, filePath, violations); + } + + return violations; +} + +/** + * Scans JavaScript or TypeScript AST string and template nodes. + * + * @param {string} source Source contents to inspect. + * @param {string} filePath File path supplied to the TypeScript parser. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @returns {void} + */ +function scanTypeScriptSource(source, filePath, violations) { + const extension = path.extname(filePath); + const scriptKind = + extension === ".tsx" + ? ts.ScriptKind.TSX + : extension === ".jsx" + ? ts.ScriptKind.JSX + : extension === ".js" || + extension === ".mjs" || + extension === ".cjs" + ? ts.ScriptKind.JS + : ts.ScriptKind.TS; + const sourceFile = ts.createSourceFile( + filePath, + source, + ts.ScriptTarget.Latest, + true, + scriptKind, + ); + + /** + * Recursively visits a node in the parsed TypeScript source. + * + * @param {ts.Node} node AST node to inspect. + * @returns {void} + */ + function visit(node) { + visitTypeScriptNode(node, sourceFile, source, violations, visit); + } + + visit(sourceFile); +} + +/** + * Visits a TypeScript AST node and checks its string-bearing children. + * + * @param {ts.Node} node AST node to inspect. + * @param {ts.SourceFile} sourceFile Parsed source file. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function visitTypeScriptNode(node, sourceFile, source, violations, visit) { + if (ts.isStringLiteral(node)) { + scanRawText( + node.getText(sourceFile), + node.getStart(sourceFile), + source, + violations, + ); + return; + } + + if (ts.isRegularExpressionLiteral(node)) return; + + if (ts.isNoSubstitutionTemplateLiteral(node)) { + scanRawText( + node.getText(sourceFile), + node.getStart(sourceFile), + source, + violations, + ); + return; + } + + if (ts.isTemplateExpression(node)) { + scanTypeScriptTemplateExpression( + node, + sourceFile, + source, + violations, + visit, + ); + return; + } + + if ( + ts.isTaggedTemplateExpression(node) && + isTypeScriptStringRawTag(node.tag) + ) { + visitTypeScriptRawTemplate(node.template, visit); + return; + } + + ts.forEachChild(node, visit); +} + +/** + * Scans an untagged TypeScript template and visits its interpolations. + * + * @param {ts.TemplateExpression} node Template expression AST node. + * @param {ts.SourceFile} sourceFile Parsed source file. + * @param {string} source Full file contents. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function scanTypeScriptTemplateExpression( + node, + sourceFile, + source, + violations, + visit, +) { + scanRawText( + node.head.getText(sourceFile), + node.head.getStart(sourceFile), + source, + violations, + ); + for (const span of node.templateSpans) { + scanRawText( + span.literal.getText(sourceFile), + span.literal.getStart(sourceFile), + source, + violations, + ); + visit(span.expression); + } +} + +/** + * Visits interpolations without scanning the raw template portions. + * + * @param {ts.TemplateLiteral} template Tagged template AST node. + * @param {(node: ts.Node) => void} visit Recursive visitor callback. + * @returns {void} + */ +function visitTypeScriptRawTemplate(template, visit) { + if (!ts.isTemplateExpression(template)) return; + for (const span of template.templateSpans) visit(span.expression); +} + +/** + * Scans Svelte script and markup-expression AST nodes. + * + * @param {string} source Svelte component contents. + * @param {string} filePath File path supplied to the Svelte parser. + * @param {EscapedLatexViolation[]} violations Mutable output collection. + * @returns {void} + */ +function scanSvelteSource(source, filePath, violations) { + const root = parseSvelte(source, { filename: filePath, modern: true }); + /** @type {WeakSet
Trigonometric Form:
Exponential Form:
Coefficient Relations:
@@ -91,7 +91,7 @@
Weak Dirichlet Condition:
@@ -105,7 +105,7 @@
Discontinuity Midpoint Convergence:
diff --git a/src/lib/math-engine/circuits.ts b/src/lib/math-engine/circuits.ts
index 6d1e83e5..39d68b60 100644
--- a/src/lib/math-engine/circuits.ts
+++ b/src/lib/math-engine/circuits.ts
@@ -420,7 +420,7 @@ export function createCircuitProblem(
id: `circuit-${topology}-${Date.now()}`,
topology,
components: { ...components },
- promptLatex: `\\text{Derive the transfer function } H(s) \\text{ for the } \\text{${name}} \\text{ with } R = ${R}\\Omega${circuitUsesInductor(topology) ? `, L = ${L}\\text{H}` : ""}${circuitUsesCapacitor(topology) ? `, C = ${C}\\text{F}` : ""}.`,
+ promptLatex: String.raw`\text{Derive the transfer function } H(s) \text{ for the } \text{${name}} \text{ with } R = ${R}\Omega${circuitUsesInductor(topology) ? String.raw`, L = ${L}\text{H}` : ""}${circuitUsesCapacitor(topology) ? String.raw`, C = ${C}\text{F}` : ""}.`,
referenceAnswerLatex: tf.hLatex,
solutionSteps: [
{
@@ -429,11 +429,11 @@ export function createCircuitProblem(
},
{
title: "Step 2: Apply Voltage Divider / Node Voltage Equations",
- latex: `H(s) = \\frac{Z_{out}(s)}{Z_{in}(s)} = ${tf.hLatex}`,
+ latex: String.raw`H(s) = \frac{Z_{out}(s)}{Z_{in}(s)} = ${tf.hLatex}`,
},
{
title: "Step 3: Identify Characteristic Parameters",
- latex: `\\text{Derived Transfer Function } H(s) = ${tf.hLatex}`,
+ latex: String.raw`\text{Derived Transfer Function } H(s) = ${tf.hLatex}`,
},
],
};
diff --git a/src/lib/math-engine/convolution/configuration.ts b/src/lib/math-engine/convolution/configuration.ts
index 7d3aa002..5e923e61 100644
--- a/src/lib/math-engine/convolution/configuration.ts
+++ b/src/lib/math-engine/convolution/configuration.ts
@@ -288,8 +288,8 @@ export function resolveConvolutionSignal(
latex: scaleLatex(
amplitude,
parameter === 2
- ? `\\Delta\\left(${argument}\\right)`
- : `\\Delta\\left(\\frac{2(${argument})}{${parameter}}\\right)`,
+ ? String.raw`\Delta\left(${argument}\right)`
+ : String.raw`\Delta\left(\frac{2(${argument})}{${parameter}}\right)`,
),
sections: [section(`${key}-1`, start, end)],
breakpoints: [start, shift, end],
diff --git a/src/lib/math-engine/convolution/configured-solver.ts b/src/lib/math-engine/convolution/configured-solver.ts
index 45ec41dc..e1e887ad 100644
--- a/src/lib/math-engine/convolution/configured-solver.ts
+++ b/src/lib/math-engine/convolution/configured-solver.ts
@@ -41,7 +41,7 @@ function scalarLatex(value: number, absolute = false): string {
const numerator = absolute ? Math.abs(rawNumerator) : rawNumerator;
return denominator === 1
? String(numerator)
- : `\\frac{${numerator}}{${denominator}}`;
+ : String.raw`\frac{${numerator}}{${denominator}}`;
}
function polynomialLatex(polynomial: Polynomial): string {
@@ -84,8 +84,8 @@ function uniqueSorted(values: number[]): number[] {
function intervalLabel(min: number, max: number): string {
if (!Number.isFinite(min)) return `t < ${scalarLatex(max)}`;
- if (!Number.isFinite(max)) return `t \\ge ${scalarLatex(min)}`;
- return `${scalarLatex(min)} \\le t < ${scalarLatex(max)}`;
+ if (!Number.isFinite(max)) return String.raw`t \ge ${scalarLatex(min)}`;
+ return String.raw`${scalarLatex(min)} \le t < ${scalarLatex(max)}`;
}
function intervalRanges(boundaries: number[]): Array<[number, number]> {
@@ -338,7 +338,7 @@ function solveExponentials(
const equalRates = Math.abs(x.parameter - h.parameter) < EPSILON;
const activeExpression = equalRates
? `${scalarLatex(coefficient)}(${formatShiftedTime(onset)})e^{-${x.parameter}(${formatShiftedTime(onset)})}`
- : `\\frac{${scalarLatex(coefficient)}}{${scalarLatex(h.parameter - x.parameter)}}\\left(e^{-${x.parameter}(${formatShiftedTime(onset)})}-e^{-${h.parameter}(${formatShiftedTime(onset)})}\\right)`;
+ : String.raw`\frac{${scalarLatex(coefficient)}}{${scalarLatex(h.parameter - x.parameter)}}\left(e^{-${x.parameter}(${formatShiftedTime(onset)})}-e^{-${h.parameter}(${formatShiftedTime(onset)})}\right)`;
const activeEval = (t: number): number => {
if (t < onset) return 0;
const elapsed = t - onset;
diff --git a/src/lib/math-engine/convolution/engine.ts b/src/lib/math-engine/convolution/engine.ts
index 0623acdc..d6362907 100644
--- a/src/lib/math-engine/convolution/engine.ts
+++ b/src/lib/math-engine/convolution/engine.ts
@@ -221,13 +221,13 @@ export function generateConfiguredConvolutionProblem(
title: "Identify the Two Configured Signals",
description:
"Record each signal's exact support, breakpoints, amplitude, and translation.",
- latex: `x(t)=${resolvedSignals.x.latex},\\quad h(t)=${resolvedSignals.h.latex}`,
+ latex: String.raw`x(t)=${resolvedSignals.x.latex},\quad h(t)=${resolvedSignals.h.latex}`,
},
{
title: "Build Every Geometric Overlap Region",
description:
"Add fixed and moving breakpoints, then integrate every connected overlap component.",
- latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau",
+ latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`,
},
{
title: "Combine Signed Contributions",
@@ -236,9 +236,9 @@ export function generateConfiguredConvolutionProblem(
latex: result.intervals
.map(
(interval) =>
- `y(t)=${interval.exprLatex}\\quad(${interval.labelLatex})`,
+ String.raw`y(t)=${interval.exprLatex}\quad(${interval.labelLatex})`,
)
- .join(",\\quad "),
+ .join(String.raw`,\quad `),
},
],
intervals: result.intervals,
diff --git a/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts b/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts
index fc55524a..e7d56a07 100644
--- a/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts
+++ b/src/lib/math-engine/convolution/its-scaffolding/evaluation-terms.ts
@@ -53,20 +53,20 @@ function polynomialEvaluationTerm(
String.raw`\tau`,
);
const movingPieceLatex = sanitizeLatexMath(
- `${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}(t-\\tau)`,
+ String.raw`${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}(t-\tau)`,
);
const p0 = `(${formatConvolutionScalar(a0)})(${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}t)`;
const p1 = `(${formatConvolutionScalar(a1)})(${formatConvolutionScalar(b0)}+${formatConvolutionScalar(b1)}t)-${formatConvolutionScalar(a0 * b1)}`;
const p2 = formatConvolutionScalar(-a1 * b1);
const integrandLatex = sanitizeLatexMath(
- `${p0}+(${p1})\\tau+(${p2})\\tau^2`,
+ String.raw`${p0}+(${p1})\tau+(${p2})\tau^2`,
);
const primitiveLatex = sanitizeLatexMath(
- `F(\\tau,t)=(${p0})\\tau+\\frac{(${p1})\\tau^2}{2}+\\frac{(${p2})\\tau^3}{3}`,
+ String.raw`F(\tau,t)=(${p0})\tau+\frac{(${p1})\tau^2}{2}+\frac{(${p2})\tau^3}{3}`,
);
const substitute = (bound: string): string =>
sanitizeLatexMath(
- `(${p0})(${bound})+\\frac{(${p1})(${bound})^2}{2}+\\frac{(${p2})(${bound})^3}{3}`,
+ String.raw`(${p0})(${bound})+\frac{(${p1})(${bound})^2}{2}+\frac{(${p2})(${bound})^3}{3}`,
);
const upperSubstitutionLatex = substitute(upperLatex);
const lowerSubstitutionLatex = substitute(lowerLatex);
@@ -166,13 +166,13 @@ function exponentialPrimitive(
rate: number,
): string {
if (Math.abs(rate) < 1e-12)
- return `${prefactor}((${timeFactor(coefficients)})\\tau${slope === 0 ? "" : `+(${toFractionLatex(slope / 2)})\\tau^2`})`;
+ return String.raw`${prefactor}((${timeFactor(coefficients)})\tau${slope === 0 ? "" : String.raw`+(${toFractionLatex(slope / 2)})\tau^2`})`;
const q0 = timeFactor([
coefficients[0] / rate - slope / (rate * rate),
coefficients[1] / rate,
]);
const q1 = slope / rate;
- return `${prefactor}e^{${formatConvolutionScalar(rate)}\\tau}((${q0})${q1 === 0 ? "" : `+(${toFractionLatex(q1)})\\tau`})`;
+ return String.raw`${prefactor}e^{${formatConvolutionScalar(rate)}\tau}((${q0})${q1 === 0 ? "" : String.raw`+(${toFractionLatex(q1)})\tau`})`;
}
/**
@@ -226,9 +226,9 @@ function exponentialEvaluationTerm(
const exponential =
Math.abs(exponentRate) < 1e-12
? ""
- : `e^{${formatConvolutionScalar(exponentRate)}\\tau}`;
+ : String.raw`e^{${formatConvolutionScalar(exponentRate)}\tau}`;
const integrandLatex = sanitizeLatexMath(
- `${prefactor}((${constant})${slope === 0 ? "" : `+(${toFractionLatex(slope)})\\tau`})${exponential}`,
+ String.raw`${prefactor}((${constant})${slope === 0 ? "" : String.raw`+(${toFractionLatex(slope)})\tau`})${exponential}`,
);
const primitiveBody = exponentialPrimitive(
prefactor,
@@ -236,7 +236,9 @@ function exponentialEvaluationTerm(
slope,
exponentRate,
);
- const primitiveLatex = sanitizeLatexMath(`F(\\tau,t)=${primitiveBody}`);
+ const primitiveLatex = sanitizeLatexMath(
+ String.raw`F(\tau,t)=${primitiveBody}`,
+ );
/** @param bound - Verified limit. @returns Primitive evaluated at that limit. */
const substitute = (bound: string): string =>
sanitizeLatexMath(
diff --git a/src/lib/math-engine/convolution/its-scaffolding/helpers.ts b/src/lib/math-engine/convolution/its-scaffolding/helpers.ts
index 727794e6..8a158a05 100644
--- a/src/lib/math-engine/convolution/its-scaffolding/helpers.ts
+++ b/src/lib/math-engine/convolution/its-scaffolding/helpers.ts
@@ -88,8 +88,8 @@ function buildTransitionGroups(
? `${moving}-${groupId}-contact-1`
: undefined,
formulationHints: [
- `The fixed breakpoint is $\\tau=${formatConvolutionScalar(fixed)}$.`,
- `After reflection and translation, moving breakpoint $${formatConvolutionScalar(movingPoint)}$ appears at $\\tau=${transformedLatex}$.`,
+ String.raw`The fixed breakpoint is $\tau=${formatConvolutionScalar(fixed)}$.`,
+ String.raw`After reflection and translation, moving breakpoint $${formatConvolutionScalar(movingPoint)}$ appears at $\tau=${transformedLatex}$.`,
`Set the breakpoint positions equal: $${equationLatex}$.`,
],
solutionHints: [
@@ -135,7 +135,7 @@ function timingPart(
start,
end,
width,
- resultLatex: `${id}_{\\mathrm{${id === "y" ? "overlap,start" : "start"}}}=${formatConvolutionScalar(start)},\\quad ${id}_{\\mathrm{${id === "y" ? "overlap,end" : "end"}}}=${formatConvolutionScalar(end)},\\quad W_{${id}${id === "y" ? ",\\mathrm{overlap}" : ""}}=${formatConvolutionScalar(width)}`,
+ resultLatex: String.raw`${id}_{\mathrm{${id === "y" ? "overlap,start" : "start"}}}=${formatConvolutionScalar(start)},\quad ${id}_{\mathrm{${id === "y" ? "overlap,end" : "end"}}}=${formatConvolutionScalar(end)},\quad W_{${id}${id === "y" ? String.raw`,\mathrm{overlap}` : ""}}=${formatConvolutionScalar(width)}`,
hints:
id === "y"
? [
@@ -194,7 +194,7 @@ export function buildConvolutionItsData(
const definitionOptions = [
{
id: "convolution-integral",
- latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau",
+ latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`,
isCorrect: true,
},
{
@@ -206,14 +206,13 @@ export function buildConvolutionItsData(
},
{
id: "correlation-integral",
- latex: "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau",
+ latex: String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau`,
isCorrect: false,
- feedback:
- "The moving argument has the wrong orientation; reflection requires $t-\\tau$.",
+ feedback: String.raw`The moving argument has the wrong orientation; reflection requires $t-\tau$.`,
},
{
id: "outside-variable",
- latex: "y(t)=x(t)\\int_{-\\infty}^{\\infty}h(t-\\tau)\\,d\\tau",
+ latex: String.raw`y(t)=x(t)\int_{-\infty}^{\infty}h(t-\tau)\,d\tau`,
isCorrect: false,
feedback:
"Both signals must depend on the integration variable inside the convolution integral.",
@@ -245,8 +244,8 @@ export function buildConvolutionItsData(
options: shuffledDefinitionOptions,
hints: [
"Convolution combines reflection, translation, multiplication, and integration.",
- "Use $\\tau$ as the integration variable while $t$ remains a parameter.",
- "One signal is fixed in $\\tau$ and the other uses $t-\\tau$.",
+ String.raw`Use $\tau$ as the integration variable while $t$ remains a parameter.`,
+ String.raw`One signal is fixed in $\tau$ and the other uses $t-\tau$.`,
],
},
step3: {
@@ -266,7 +265,7 @@ export function buildConvolutionItsData(
},
choiceHints: [
"Both choices produce the same convolution because convolution is commutative.",
- "Keep one signal fixed in $\\tau$ and reflect and translate the other.",
+ String.raw`Keep one signal fixed in $\tau$ and reflect and translate the other.`,
"Choose the shape whose reflected edges are easiest for you to track.",
],
edgeHints: [
@@ -336,7 +335,7 @@ export function buildConvolutionItsData(
intervalBuilderHints: [
"Use the verified transition times from smallest to largest.",
"The first interval is left-unbounded and the final interval is right-unbounded.",
- `The ordered boundaries are $${intervalBoundaries.map(formatConvolutionScalar).join(",\\;")}$.`,
+ String.raw`The ordered boundaries are $${intervalBoundaries.map(formatConvolutionScalar).join(String.raw`,\;`)}$.`,
],
},
step5: {
diff --git a/src/lib/math-engine/convolution/its-scaffolding/intervals.ts b/src/lib/math-engine/convolution/its-scaffolding/intervals.ts
index 16c475d3..e9724354 100644
--- a/src/lib/math-engine/convolution/its-scaffolding/intervals.ts
+++ b/src/lib/math-engine/convolution/its-scaffolding/intervals.ts
@@ -120,7 +120,7 @@ function buildPathSetup(
.slice(0, -1)
.map(
(lower, index) =>
- `\\int_{${lower}}^{${boundaries[index + 1]}}${fixedName}(\\tau)${movingSignal}(t-\\tau)\\,d\\tau`,
+ String.raw`\int_{${lower}}^{${boundaries[index + 1]}}${fixedName}(\tau)${movingSignal}(t-\tau)\,d\tau`,
);
});
return {
@@ -167,10 +167,10 @@ export function buildSetupPart(
];
const lowerCandidates = setup.overlaps
.map(({ lowerCandidatesLatex }) => lowerCandidatesLatex.join(","))
- .join(";\\;");
+ .join(String.raw`;\;`);
const upperCandidates = setup.overlaps
.map(({ upperCandidatesLatex }) => upperCandidatesLatex.join(","))
- .join(";\\;");
+ .join(String.raw`;\;`);
const splitPoints = setup.overlaps.flatMap(
({ splitPointsLatex }) => splitPointsLatex,
);
@@ -178,7 +178,7 @@ export function buildSetupPart(
`Use the representative interior time $t=${formatConvolutionScalar(representativeTime(interval))}$ for $${interval.labelLatex}$.`,
`Compare lower candidates $${lowerCandidates}$ and upper candidates $${upperCandidates}$.`,
splitPoints.length > 0
- ? `Split at $${splitPoints.join(",\\;")}$.`
+ ? String.raw`Split at $${splitPoints.join(String.raw`,\;`)}$.`
: `The verified setup is $${setup.integralLatex}$.`,
];
};
@@ -245,7 +245,7 @@ export function buildEvaluationPart(
id: `interval-${String(index + 1).padStart(2, "0")}`,
title: `Evaluate Region ${index + 1}`,
intervalLatex: interval.labelLatex,
- resultLatex: `y(t)=${interval.exprLatex},\\quad ${interval.labelLatex}`,
+ resultLatex: String.raw`y(t)=${interval.exprLatex},\quad ${interval.labelLatex}`,
options: [],
carriedZero,
primitiveLatex: carriedZero ? "0" : primitiveBySignal.h,
diff --git a/src/lib/math-engine/convolution/its-scaffolding/presentation.ts b/src/lib/math-engine/convolution/its-scaffolding/presentation.ts
index b9cdfcfa..077f8627 100644
--- a/src/lib/math-engine/convolution/its-scaffolding/presentation.ts
+++ b/src/lib/math-engine/convolution/its-scaffolding/presentation.ts
@@ -18,8 +18,8 @@ import { createSeededPrng, shuffleWithRandom } from "$lib/math-engine/random";
/** Formats one finite or infinite scalar as exact LaTeX. */
export function formatConvolutionScalar(value: number): string {
- if (value === Number.POSITIVE_INFINITY) return "\\infty";
- if (value === Number.NEGATIVE_INFINITY) return "-\\infty";
+ if (value === Number.POSITIVE_INFINITY) return String.raw`\infty`;
+ if (value === Number.NEGATIVE_INFINITY) return String.raw`-\infty`;
return String(value);
}
@@ -33,7 +33,7 @@ export function formatConvolutionPiecewiseLatex(
`${expressions[index] ?? interval.exprLatex} & ${interval.labelLatex}`,
);
return sanitizeLatexMath(
- `y(t) = \\begin{cases} ${rows.join(" \\\\ ")} \\end{cases}`,
+ String.raw`y(t) = \begin{cases} ${rows.join(String.raw` \\ `)} \end{cases}`,
);
}
@@ -52,8 +52,8 @@ export function getFiniteConvolutionTransitionTimes(
/** Formats one transformed moving edge. */
export function formatTranslatedEdge(value: number): string {
- if (value === Number.POSITIVE_INFINITY) return "-\\infty";
- if (value === Number.NEGATIVE_INFINITY) return "\\infty";
+ if (value === Number.POSITIVE_INFINITY) return String.raw`-\infty`;
+ if (value === Number.NEGATIVE_INFINITY) return String.raw`\infty`;
return formatTranslatedArgument("t", value);
}
@@ -94,28 +94,27 @@ export function buildFormulaStep(
): ConvolutionItsChoiceStep {
const matching =
moving === "h"
- ? "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau"
- : "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(t-\\tau)\\,d\\tau";
+ ? String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`
+ : String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(t-\tau)\,d\tau`;
const selectedWithoutFlip =
moving === "h"
- ? "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau"
- : "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(\\tau-t)\\,d\\tau";
+ ? String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau`
+ : String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(\tau-t)\,d\tau`;
const otherCorrect =
moving === "h"
- ? "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(t-\\tau)\\,d\\tau"
- : "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(t-\\tau)\\,d\\tau";
+ ? String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(t-\tau)\,d\tau`
+ : String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(t-\tau)\,d\tau`;
const otherWithoutFlip =
moving === "h"
- ? "y(t)=\\int_{-\\infty}^{\\infty}h(\\tau)x(\\tau-t)\\,d\\tau"
- : "y(t)=\\int_{-\\infty}^{\\infty}x(\\tau)h(\\tau-t)\\,d\\tau";
+ ? String.raw`y(t)=\int_{-\infty}^{\infty}h(\tau)x(\tau-t)\,d\tau`
+ : String.raw`y(t)=\int_{-\infty}^{\infty}x(\tau)h(\tau-t)\,d\tau`;
const options: ConvolutionItsOption[] = [
{ id: `formula-${moving}-correct`, latex: matching, isCorrect: true },
{
id: `formula-${moving}-no-flip`,
latex: selectedWithoutFlip,
isCorrect: false,
- feedback:
- "This shifts the selected signal without reflecting it. The moving argument must be $t-\\tau$.",
+ feedback: String.raw`This shifts the selected signal without reflecting it. The moving argument must be $t-\tau$.`,
},
{
id: `formula-${moving}-other-path`,
@@ -135,11 +134,11 @@ export function buildFormulaStep(
const optionSeed =
(seed ^ (moving === "x" ? 0x58_33_ba_11 : 0x48_33_ba_11)) >>> 0;
return {
- prompt: `Which integral keeps $${moving === "h" ? "x" : "h"}(\\tau)$ fixed and moves $${moving}(t)$?`,
+ prompt: String.raw`Which integral keeps $${moving === "h" ? "x" : "h"}(\tau)$ fixed and moves $${moving}(t)$?`,
options: shuffleWithRandom(options, createSeededPrng(optionSeed)),
hints: [
- "The fixed signal keeps the argument $\\tau$.",
- "The selected moving signal receives the argument $t-\\tau$.",
+ String.raw`The fixed signal keeps the argument $\tau$.`,
+ String.raw`The selected moving signal receives the argument $t-\tau$.`,
`The matching path is $${matching}$.`,
],
};
diff --git a/src/lib/math-engine/convolution/pulse-formatting.ts b/src/lib/math-engine/convolution/pulse-formatting.ts
index 75377e56..5a23fbff 100644
--- a/src/lib/math-engine/convolution/pulse-formatting.ts
+++ b/src/lib/math-engine/convolution/pulse-formatting.ts
@@ -36,7 +36,7 @@ export function formatRectPulseLatex(
const argument = formatTranslatedArgument("t", shift);
const body =
width === 1
- ? `\\operatorname{rect}(${argument})`
- : `\\operatorname{rect}\\left(\\frac{${argument}}{${width}}\\right)`;
+ ? String.raw`\operatorname{rect}(${argument})`
+ : String.raw`\operatorname{rect}\left(\frac{${argument}}{${width}}\right)`;
return sanitizeLatexMath(formatPulseScale(amplitude, body));
}
diff --git a/src/lib/math-engine/evaluator.ts b/src/lib/math-engine/evaluator.ts
index 1efeca87..e08b58df 100644
--- a/src/lib/math-engine/evaluator.ts
+++ b/src/lib/math-engine/evaluator.ts
@@ -94,7 +94,10 @@ export function parseStrictLatex(latex: string): unknown {
(token: string): string =>
token.startsWith("\\")
? token
- : token.replace(/u\s*$/, "\\operatorname{Heaviside}"),
+ : token.replace(
+ /u\s*$/,
+ String.raw`\operatorname{Heaviside}`,
+ ),
);
return parse(normalizeMathLatex(expression, false));
}
@@ -124,13 +127,16 @@ export function normalizeMathLatex(
return (
normalized
// Convert bare 'pi' followed by a variable (e.g. 100pit -> 100\pi t, pit -> \pi t)
- .replace(/(^|[^a-zA-Z\\])pi([a-zA-Z])(?=[^a-zA-Z]|$)/g, "$1\\pi $2")
+ .replace(
+ /(^|[^a-zA-Z\\])pi([a-zA-Z])(?=[^a-zA-Z]|$)/g,
+ String.raw`$1\pi $2`,
+ )
// Convert standalone bare 'pi' (e.g. 100pi t -> 100\pi t, 2*pi -> 2*\pi)
- .replace(/(^|[^a-zA-Z\\])pi(?=[^a-zA-Z]|$)/g, "$1\\pi")
+ .replace(/(^|[^a-zA-Z\\])pi(?=[^a-zA-Z]|$)/g, String.raw`$1\pi`)
// Convert bare functions without leading backslash (e.g. cos, sin, tan, exp, sqrt, ln, log)
.replace(
/(^|[^a-zA-Z\\])(cos|sin|tan|exp|sqrt|ln|log)(?=[^a-zA-Z]|$)/g,
- "$1\\$2",
+ String.raw`$1\$2`,
)
);
}
@@ -303,7 +309,7 @@ export function evaluatePiecewiseLatexAt(latex: string, t: number): number {
const body = match[1];
const rows = body
- .split("\\\\")
+ .split(String.raw`\\`)
.map((r) => r.trim())
.filter(Boolean);
@@ -315,8 +321,8 @@ export function evaluatePiecewiseLatexAt(latex: string, t: number): number {
const parts = row.split("&");
exprPart = (parts[0] ?? "").trim().replace(/[,;]$/, "").trim();
condPart = parts.slice(1).join("&").trim();
- } else if (row.includes("\\text{for}")) {
- const parts = row.split("\\text{for}");
+ } else if (row.includes(String.raw`\text{for}`)) {
+ const parts = row.split(String.raw`\text{for}`);
exprPart = (parts[0] ?? "")
.trim()
.replace(/\\quad$/, "")
diff --git a/src/lib/math-engine/formatting.ts b/src/lib/math-engine/formatting.ts
index 0cac827c..46c8657a 100644
--- a/src/lib/math-engine/formatting.ts
+++ b/src/lib/math-engine/formatting.ts
@@ -114,8 +114,8 @@ export function formatQuadraticPolynomial(
*/
export function formatOdeLhs(a2: number, a1: number, a0: number): string {
const terms: PolynomialTerm[] = [
- { coeff: a2, symbol: "\\frac{d^2 y}{dt^2}" },
- { coeff: a1, symbol: "\\frac{dy}{dt}" },
+ { coeff: a2, symbol: String.raw`\frac{d^2 y}{dt^2}` },
+ { coeff: a1, symbol: String.raw`\frac{dy}{dt}` },
{ coeff: a0, symbol: "y(t)" },
];
@@ -301,7 +301,7 @@ export function sanitizeUnitCoefficients(latex: string): string {
// Lookaround ensures we do NOT match multi-digit numbers like j10, j11, -j10, 10j, 31j, 151j, 0.1j
s = s.replace(/(? x, -1x -> -x, + 1t -> + t, - 1t -> - t, (1t -> (t, (-1t -> (-t
@@ -320,17 +320,17 @@ export function sanitizeUnitCoefficients(latex: string): string {
// Lookahead (?![0-9]) preserves \cos(10t), \cos(11t), \sin(151t)
s = s.replace(
/\\(cos|sin|tan|cot|sec|csc)\(\s*(-?)1([a-zA-Z])(?![0-9])\s*\)/g,
- "\\$1($2$3)",
+ String.raw`\$1($2$3)`,
);
s = s.replace(
/\\(cos|sin|tan|cot|sec|csc)\(\s*(-?)j1([a-zA-Z])(?![0-9])\s*\)/g,
- "\\$1($2j$3)",
+ String.raw`\$1($2j$3)`,
);
// Unit multiplier before functions: 1\cos -> \cos, -1\cos -> -\cos, 1e^{ -> e^{
s = s.replace(
/(?0$, use $c_n=2|F_n|=\\sqrt{a_n^2+b_n^2}$.",
- "Assign phase only to nonzero harmonics with $\\theta_n=\\operatorname{atan2}(-b_n,a_n)=\\angle F_n$.",
+ String.raw`For $n>0$, use $c_n=2|F_n|=\sqrt{a_n^2+b_n^2}$.`,
+ String.raw`Assign phase only to nonzero harmonics with $\theta_n=\operatorname{atan2}(-b_n,a_n)=\angle F_n$.`,
],
},
],
@@ -121,13 +121,13 @@ export function generateFourierSeriesProblem(
title: "Period and Fundamental Frequency",
description:
"Read one complete repetition from the waveform and convert its period to angular frequency.",
- latex: `T_0=${periodLatex}\\text{ s},\\qquad \\omega_0=\\frac{2\\pi}{T_0}=\\frac{2\\pi}{${periodLatex}}=${w0Latex}\\text{ rad/s}`,
+ latex: String.raw`T_0=${periodLatex}\text{ s},\qquad \omega_0=\frac{2\pi}{T_0}=\frac{2\pi}{${periodLatex}}=${w0Latex}\text{ rad/s}`,
},
{
title: "Symmetry and Vanishing Terms",
description:
"Test origin parity and half-wave symmetry independently, then remove coefficient families that must vanish.",
- latex: `\\begin{gathered}\\text{origin parity: }${coeffs.originParity},\\qquad \\text{half-wave symmetry: }${coeffs.hasHalfWaveSymmetry ? "\\text{yes}" : "\\text{no}"}\\\\${coeffs.originParity === "odd" ? "a_0=a_n=0" : coeffs.originParity === "even" ? "b_n=0" : "a_n\\text{ and }b_n\\text{ must both be evaluated}"}\\end{gathered}`,
+ latex: String.raw`\begin{gathered}\text{origin parity: }${coeffs.originParity},\qquad \text{half-wave symmetry: }${coeffs.hasHalfWaveSymmetry ? String.raw`\text{yes}` : String.raw`\text{no}`}\\${coeffs.originParity === "odd" ? String.raw`a_0=a_n=0` : coeffs.originParity === "even" ? String.raw`b_n=0` : String.raw`a_n\text{ and }b_n\text{ must both be evaluated}`}\end{gathered}`,
},
{
title: "Representation Selection",
@@ -137,8 +137,8 @@ export function generateFourierSeriesProblem(
: "The assigned trigonometric path evaluates the real coefficient families remaining after symmetry shortcuts.",
latex:
itsData.step4.correctForm === "exp"
- ? "F_n=\\frac{1}{T_0}\\int_{T_0}x(t)e^{-jn\\omega_0t}\\,dt"
- : "x(t)=\\frac{a_0}{2}+\\sum_{n=1}^{\\infty}[a_n\\cos(n\\omega_0t)+b_n\\sin(n\\omega_0t)]",
+ ? String.raw`F_n=\frac{1}{T_0}\int_{T_0}x(t)e^{-jn\omega_0t}\,dt`
+ : String.raw`x(t)=\frac{a_0}{2}+\sum_{n=1}^{\infty}[a_n\cos(n\omega_0t)+b_n\sin(n\omega_0t)]`,
},
{
title: "Piecewise Integral Setup",
@@ -147,12 +147,11 @@ export function generateFourierSeriesProblem(
latex:
itsData.step4.correctForm === "exp"
? derivation.expIntegralLatex
- : `\\begin{gathered}${itsData.step5.parts.map(({ resultLatex }) => resultLatex).join("\\\\")}\\end{gathered}`,
+ : String.raw`\begin{gathered}${itsData.step5.parts.map(({ resultLatex }) => resultLatex).join(String.raw`\\`)}\end{gathered}`,
},
{
title: "Definite Integral Evaluation",
- description:
- "Apply the bounds and simplify parity factors such as $(-1)^n$ and $\\sin(n\\pi/2)$.",
+ description: String.raw`Apply the bounds and simplify parity factors such as $(-1)^n$ and $\sin(n\pi/2)$.`,
latex:
itsData.step4.correctForm === "exp"
? getExponentialEvaluationLatex(derivation)
@@ -162,7 +161,7 @@ export function generateFourierSeriesProblem(
title: "DC Offset Derivation",
description:
"Evaluate the average separately; the constant appearing in the trigonometric series is $a_0/2$.",
- latex: `a_0=\\frac{2}{T_0}\\int_{T_0}x(t)\\,dt=${derivation.a0Latex},\\qquad F_0=\\frac{a_0}{2}`,
+ latex: String.raw`a_0=\frac{2}{T_0}\int_{T_0}x(t)\,dt=${derivation.a0Latex},\qquad F_0=\frac{a_0}{2}`,
},
{
title: `${primaryName} Synthesis`,
@@ -182,8 +181,8 @@ export function generateFourierSeriesProblem(
seed,
waveformType,
title: "Practice Problem: Periodic Waveform",
- periodLatex: `T_0 = ${periodLatex}\\text{ s}`,
- omega0Latex: `\\omega_0 = \\frac{2\\pi}{${periodLatex}} = ${w0Latex}\\text{ rad/s}`,
+ periodLatex: String.raw`T_0 = ${periodLatex}\text{ s}`,
+ omega0Latex: String.raw`\omega_0 = \frac{2\pi}{${periodLatex}} = ${w0Latex}\text{ rad/s}`,
signalLatex,
a0Latex: derivation.a0Latex,
anLatex: derivation.anLatex,
diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts
index ca1ba191..34e485d5 100644
--- a/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts
+++ b/src/lib/math-engine/fourier-series/its-scaffolding/step1-period-freq.ts
@@ -24,9 +24,16 @@ export function buildStep1Data(
const periodLatex = formatFourierNumber(T0);
const w0Aliases =
T0 === 2
- ? ["pi", "\\pi", "1pi", "3.14", "3.1415", "3.1416"]
+ ? ["pi", String.raw`\pi`, "1pi", "3.14", "3.1415", "3.1416"]
: T0 === 4
- ? ["pi/2", "\\pi/2", "0.5pi", "0.5\\pi", "1.57", "1.5708"]
+ ? [
+ "pi/2",
+ String.raw`\pi/2`,
+ "0.5pi",
+ String.raw`0.5\pi`,
+ "1.57",
+ "1.5708",
+ ]
: [w0Latex, formatFourierNumber(w0)];
return {
@@ -38,8 +45,8 @@ export function buildStep1Data(
w0Aliases,
hints: [
"Look at the bounds of the definition. Over what duration does the signal repeat itself entirely?",
- `The signal repeats every period $T_0 = ${periodLatex}\\text{ s}$. The fundamental frequency is $\\omega_0 = \\frac{2\\pi}{T_0}$.`,
- `Substitute $T_0 = ${periodLatex}$: $\\omega_0 = \\frac{2\\pi}{${periodLatex}} = ${w0Latex}\\text{ rad/s}$. Ensure units are $\\text{s}$ and $\\text{rad/s}$.`,
+ String.raw`The signal repeats every period $T_0 = ${periodLatex}\text{ s}$. The fundamental frequency is $\omega_0 = \frac{2\pi}{T_0}$.`,
+ String.raw`Substitute $T_0 = ${periodLatex}$: $\omega_0 = \frac{2\pi}{${periodLatex}} = ${w0Latex}\text{ rad/s}$. Ensure units are $\text{s}$ and $\text{rad/s}$.`,
],
};
}
diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts
index 487197f9..a5dfa95c 100644
--- a/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts
+++ b/src/lib/math-engine/fourier-series/its-scaffolding/step4-form.ts
@@ -30,7 +30,7 @@ export function buildStep4Data(
correctForm,
hints: [
`This guided problem uses the ${assignedName} form. Both Trigonometric and Exponential representations are mathematically valid.`,
- "Trigonometric form separates $a_n$ and $b_n$. Exponential form $F_n$ combines them using $e^{-j n \\omega_0 t}$.",
+ String.raw`Trigonometric form separates $a_n$ and $b_n$. Exponential form $F_n$ combines them using $e^{-j n \omega_0 t}$.`,
correctForm === "trig"
? "Follow the Trigonometric path by evaluating DC and the real coefficient families not already eliminated by symmetry."
: "Follow the Exponential path by evaluating $F_n$, including its DC case separately.",
@@ -38,8 +38,7 @@ export function buildStep4Data(
misconceptions: {
trig: `Trigonometric form is valid. Select the assigned ${assignedName} form for this guided derivation.`,
exp: `Exponential form is valid. Select the assigned ${assignedName} form for this guided derivation.`,
- compact:
- "Compact polar form ($C_n, \\theta_n$) is derived from Trigonometric or Exponential coefficients, not integrated directly.",
+ compact: String.raw`Compact polar form ($C_n, \theta_n$) is derived from Trigonometric or Exponential coefficients, not integrated directly.`,
},
};
}
diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts
index b5dca302..0288bbdf 100644
--- a/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts
+++ b/src/lib/math-engine/fourier-series/its-scaffolding/step5-integrals.ts
@@ -43,23 +43,47 @@ export function buildIntegralOptions(
}),
}));
}
- const scalingDistractor = correct.includes("\\frac{4}{T_0}")
- ? correct.replace("\\frac{4}{T_0}", "\\frac{2}{T_0}")
- : correct.includes("\\frac{2j}{T_0}")
- ? correct.replace("\\frac{2j}{T_0}", "\\frac{j}{T_0}")
- : correct.includes("\\frac{2}{T_0}")
- ? correct.replace("\\frac{2}{T_0}", "\\frac{1}{T_0}")
- : correct.replace("\\frac{1}{T_0}", "\\frac{2}{T_0}");
- const kernelDistractor = correct.includes("e^{-jn\\omega_0t}")
- ? correct.replace("e^{-jn\\omega_0t}", "e^{+jn\\omega_0t}")
- : correct.includes("\\cos(n\\omega_0t)")
- ? correct.replaceAll("\\cos(n\\omega_0t)", "\\sin(n\\omega_0t)")
- : correct.includes("\\sin(n\\omega_0t)")
- ? correct.replaceAll("\\sin(n\\omega_0t)", "\\cos(n\\omega_0t)")
- : correct.replace("\\,dt", "\\cos(n\\omega_0t)\\,dt");
- const fullIntervalDistractor = correct.includes("\\int_0^{T_0/2}")
- ? correct.replace("\\int_0^{T_0/2}", "\\int_0^{T_0}")
- : correct.replace("\\int_0^{T_0/4}", "\\int_0^{T_0/2}");
+ const scalingDistractor = correct.includes(String.raw`\frac{4}{T_0}`)
+ ? correct.replace(String.raw`\frac{4}{T_0}`, String.raw`\frac{2}{T_0}`)
+ : correct.includes(String.raw`\frac{2j}{T_0}`)
+ ? correct.replace(
+ String.raw`\frac{2j}{T_0}`,
+ String.raw`\frac{j}{T_0}`,
+ )
+ : correct.includes(String.raw`\frac{2}{T_0}`)
+ ? correct.replace(
+ String.raw`\frac{2}{T_0}`,
+ String.raw`\frac{1}{T_0}`,
+ )
+ : correct.replace(
+ String.raw`\frac{1}{T_0}`,
+ String.raw`\frac{2}{T_0}`,
+ );
+ const kernelDistractor = correct.includes(String.raw`e^{-jn\omega_0t}`)
+ ? correct.replace(
+ String.raw`e^{-jn\omega_0t}`,
+ String.raw`e^{+jn\omega_0t}`,
+ )
+ : correct.includes(String.raw`\cos(n\omega_0t)`)
+ ? correct.replaceAll(
+ String.raw`\cos(n\omega_0t)`,
+ String.raw`\sin(n\omega_0t)`,
+ )
+ : correct.includes(String.raw`\sin(n\omega_0t)`)
+ ? correct.replaceAll(
+ String.raw`\sin(n\omega_0t)`,
+ String.raw`\cos(n\omega_0t)`,
+ )
+ : correct.replace(
+ String.raw`\,dt`,
+ String.raw`\cos(n\omega_0t)\,dt`,
+ );
+ const fullIntervalDistractor = correct.includes(String.raw`\int_0^{T_0/2}`)
+ ? correct.replace(String.raw`\int_0^{T_0/2}`, String.raw`\int_0^{T_0}`)
+ : correct.replace(
+ String.raw`\int_0^{T_0/4}`,
+ String.raw`\int_0^{T_0/2}`,
+ );
return [
{ id: "c1", latex: correct, isCorrect: true },
@@ -74,8 +98,8 @@ export function buildIntegralOptions(
id: "d2",
latex: kernelDistractor,
isCorrect: false,
- feedback: correct.includes("e^{-jn\\omega_0t}")
- ? "Sign Error: Exponential Fourier coefficients require the kernel $e^{-j n \\omega_0 t}$."
+ feedback: correct.includes(String.raw`e^{-jn\omega_0t}`)
+ ? String.raw`Sign Error: Exponential Fourier coefficients require the kernel $e^{-j n \omega_0 t}$.`
: "Kernel Error: The selected sine or cosine kernel does not match the non-zero coefficient family.",
},
{
@@ -224,7 +248,7 @@ export function buildStep5Data(
carriedCoefficients,
hints: [
"Use symmetry to choose the non-zero coefficient family before writing an integral.",
- "Trigonometric coefficients use $2/T_0$; exponential coefficients use $1/T_0$ and $e^{-jn\\omega_0t}$.",
+ String.raw`Trigonometric coefficients use $2/T_0$; exponential coefficients use $1/T_0$ and $e^{-jn\omega_0t}$.`,
"Split the integral exactly where the waveform definition changes and omit intervals where the signal is zero.",
],
};
diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts
index 02450011..d0ba995c 100644
--- a/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts
+++ b/src/lib/math-engine/fourier-series/its-scaffolding/step6-evaluation.ts
@@ -53,21 +53,21 @@ export function buildEvaluationOptions(
},
{
id: `${target}-scale`,
- latex: `${label}=\\frac{1}{2}\\left(${resultLatex}\\right)`,
+ latex: String.raw`${label}=\frac{1}{2}\left(${resultLatex}\right)`,
isCorrect: false,
feedback:
"Scale Factor Error: Recheck the Fourier normalization before applying the integration bounds.",
},
{
id: `${target}-sign`,
- latex: `${label}=-\\left(${resultLatex}\\right)`,
+ latex: String.raw`${label}=-\left(${resultLatex}\right)`,
isCorrect: false,
feedback:
"Sign Error: Re-evaluate the antiderivative at the upper and lower bounds in order.",
},
{
id: `${target}-support`,
- latex: `${label}=2\\left(${resultLatex}\\right)`,
+ latex: String.raw`${label}=2\left(${resultLatex}\right)`,
isCorrect: false,
feedback:
"Scale Factor Error: Do not apply the Fourier normalization a second time.",
@@ -136,7 +136,7 @@ export function buildStep6Data(
carriedCoefficients,
hints: [
"Apply the antiderivative to every non-zero interval before simplifying the harmonic index.",
- "Use $\\cos(n\\pi)=(-1)^n$ and $\\sin(n\\pi/2)$ to expose vanished or alternating harmonics.",
+ String.raw`Use $\cos(n\pi)=(-1)^n$ and $\sin(n\pi/2)$ to expose vanished or alternating harmonics.`,
form === "exp"
? `The exponential integral evaluates to $${getExponentialEvaluationLatex(derivation)}$.`
: `The evaluated result is $${derivation.evaluationLatex}$.`,
diff --git a/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts b/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts
index 9e3209fc..ae4a42b3 100644
--- a/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts
+++ b/src/lib/math-engine/fourier-series/its-scaffolding/step7-series.ts
@@ -22,14 +22,14 @@ export function buildPrimarySeriesOptions(
form: FourierPrimaryForm,
): FourierItsOption[] {
// Coefficient definitions follow the synthesis expression and must stay intact.
- const definitionIndex = correct.indexOf(",\\qquad");
+ const definitionIndex = correct.indexOf(String.raw`,\qquad`);
const synthesis =
definitionIndex < 0 ? correct : correct.slice(0, definitionIndex);
const definitions =
definitionIndex < 0 ? "" : correct.slice(definitionIndex);
const rhs = synthesis.slice(synthesis.indexOf("=") + 1).trim();
- const signDistractor = `x(t)=-\\left(${rhs}\\right)${definitions}`;
- const scaleDistractor = `x(t)=\\frac{1}{2}\\left(${rhs}\\right)${definitions}`;
+ const signDistractor = String.raw`x(t)=-\left(${rhs}\right)${definitions}`;
+ const scaleDistractor = String.raw`x(t)=\frac{1}{2}\left(${rhs}\right)${definitions}`;
// Double only the independent time symbol; preserve phase and coefficient symbols.
const doubledTime = rhs.replace(/(?
- `x(t)=\\frac{c_0}{2}+\\sum_{n=1}^{\\infty}c_n\\cos(n ${w0Latex} t+\\theta_n),\\qquad ${body}`;
+ String.raw`x(t)=\frac{c_0}{2}+\sum_{n=1}^{\infty}c_n\cos(n ${w0Latex} t+\theta_n),\qquad ${body}`;
switch (waveformType) {
case "square":
case "square_odd":
return harmonic(
- `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{4(${A})}{n\\pi},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=-\\dfrac{\\pi}{2}\\ (n\\text{ odd})`,
+ String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{4(${A})}{n\pi},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=-\dfrac{\pi}{2}\ (n\text{ odd})`,
);
case "square_even":
return harmonic(
- `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{4(${A})}{n\\pi},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=\\begin{cases}0,&n\\equiv1\\pmod4\\\\\\pi,&n\\equiv3\\pmod4\\end{cases}`,
+ String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{4(${A})}{n\pi},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=\begin{cases}0,&n\equiv1\pmod4\\\pi,&n\equiv3\pmod4\end{cases}`,
);
case "triangle":
case "triangle_even":
return harmonic(
- `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{8(${A})}{n^2\\pi^2},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=0\\ (n\\text{ odd})`,
+ String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{8(${A})}{n^2\pi^2},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=0\ (n\text{ odd})`,
);
case "triangle_odd":
return harmonic(
- `c_0=0,\\quad c_n=\\begin{cases}\\dfrac{8(${A})}{n^2\\pi^2},&n\\text{ odd}\\\\0,&n\\text{ even}\\end{cases},\\quad \\theta_n=\\begin{cases}-\\dfrac{\\pi}{2},&n\\equiv1\\pmod4\\\\\\dfrac{\\pi}{2},&n\\equiv3\\pmod4\\end{cases}`,
+ String.raw`c_0=0,\quad c_n=\begin{cases}\dfrac{8(${A})}{n^2\pi^2},&n\text{ odd}\\0,&n\text{ even}\end{cases},\quad \theta_n=\begin{cases}-\dfrac{\pi}{2},&n\equiv1\pmod4\\\dfrac{\pi}{2},&n\equiv3\pmod4\end{cases}`,
);
case "sawtooth":
return harmonic(
- `c_0=0,\\quad c_n=\\dfrac{2(${A})}{n\\pi},\\quad \\theta_n=\\dfrac{(-1)^n\\pi}{2}`,
+ String.raw`c_0=0,\quad c_n=\dfrac{2(${A})}{n\pi},\quad \theta_n=\dfrac{(-1)^n\pi}{2}`,
);
case "half_wave_sine":
return harmonic(
- `c_0=\\dfrac{2(${A})}{\\pi},\\quad c_1=\\dfrac{${A}}{2},\\ \\theta_1=-\\dfrac{\\pi}{2},\\quad c_{2k}=\\dfrac{2(${A})}{\\pi(4k^2-1)},\\ \\theta_{2k}=\\pi,\\quad c_n=0\\ (n>1\\text{ odd})`,
+ String.raw`c_0=\dfrac{2(${A})}{\pi},\quad c_1=\dfrac{${A}}{2},\ \theta_1=-\dfrac{\pi}{2},\quad c_{2k}=\dfrac{2(${A})}{\pi(4k^2-1)},\ \theta_{2k}=\pi,\quad c_n=0\ (n>1\text{ odd})`,
);
case "full_wave_sine":
return harmonic(
- `c_0=\\dfrac{4(${A})}{\\pi},\\quad c_n=\\dfrac{4(${A})}{\\pi(4n^2-1)},\\quad \\theta_n=\\pi`,
+ String.raw`c_0=\dfrac{4(${A})}{\pi},\quad c_n=\dfrac{4(${A})}{\pi(4n^2-1)},\quad \theta_n=\pi`,
);
default: {
const _exhaustiveCheck: never = waveformType;
@@ -129,20 +129,20 @@ export function buildSignalLatex(
switch (waveformType) {
case "square":
case "square_odd":
- return `x(t)=\\begin{cases}-${A}&-${halfPeriod}&\'text';
- const source = kind === "macro" ? `\\text{${markup}}` : markup;
+ const source =
+ kind === "macro" ? String.raw`\text{${markup}}` : markup;
const text =
kind === "inline"
? `$${source}$`
@@ -155,7 +156,7 @@ describe("MathText.svelte Component", () => {
it("defensively renders standalone un-enclosed LaTeX macros", () => {
const { container } = render(MathText, {
props: {
- text: "The angular frequency is \\omega_0 rad/s.",
+ text: String.raw`The angular frequency is \omega_0 rad/s.`,
},
});
@@ -178,7 +179,7 @@ describe("MathText.svelte Component", () => {
it("applies optional custom class names to wrapper span", () => {
const { container } = render(MathText, {
props: {
- text: "Sample text $t \\ge 0$",
+ text: String.raw`Sample text $t \ge 0$`,
class: "custom-text-wrapper",
},
});
diff --git a/tests/unit/components/OdeResponseInput.test.ts b/tests/unit/components/OdeResponseInput.test.ts
index 239d0853..df189ac5 100644
--- a/tests/unit/components/OdeResponseInput.test.ts
+++ b/tests/unit/components/OdeResponseInput.test.ts
@@ -127,8 +127,8 @@ describe("OdeResponseInput.svelte Component", () => {
expect(handleChange).toHaveBeenCalled();
const lastCall = handleChange.mock.calls.at(-1)?.[0];
expect(lastCall).toContain("e^{-2t}");
- expect(lastCall).toContain("\\cos(5t)");
- expect(lastCall).toContain("\\sin(5t)");
+ expect(lastCall).toContain(String.raw`\cos(5t)`);
+ expect(lastCall).toContain(String.raw`\sin(5t)`);
});
it("switches to first order mode and synthesizes single exponential response", async () => {
diff --git a/tests/unit/configured-convolution.test.ts b/tests/unit/configured-convolution.test.ts
index bd788b96..df0ffc6c 100644
--- a/tests/unit/configured-convolution.test.ts
+++ b/tests/unit/configured-convolution.test.ts
@@ -237,7 +237,7 @@ describe("independently configured convolution signals", () => {
);
expect(triangle.parameter).toBe(2);
expect(triangle.breakpoints).toEqual([-1, 0, 1]);
- expect(triangle.latex).toBe("\\Delta\\left(t\\right)");
+ expect(triangle.latex).toBe(String.raw`\Delta\left(t\right)`);
expect(triangle.eval(-1)).toBe(0);
expect(triangle.eval(0)).toBe(1);
expect(triangle.eval(0.5)).toBe(0.5);
diff --git a/tests/unit/constant-proofs.test.ts b/tests/unit/constant-proofs.test.ts
index 41fad8cc..2b3df7dd 100644
--- a/tests/unit/constant-proofs.test.ts
+++ b/tests/unit/constant-proofs.test.ts
@@ -163,13 +163,13 @@ describe("constant proof boundaries", () => {
/** Domain failures survive rewrites and boxed AST wrappers. */
it("refuses canceled or masked uncertain divisors and invalid domains", () => {
for (const [decimal, multiple] of roundedPi) {
- const c = `${decimal}-${multiple}\\pi`;
+ const c = String.raw`${decimal}-${multiple}\pi`;
for (const expression of [
`0/(${c})`,
`(${c})/(${c})`,
`1/(1/(${c}))`,
- `0\\ln(${c})`,
- `0\\sqrt{${c}}`,
+ String.raw`0\ln(${c})`,
+ String.raw`0\sqrt{${c}}`,
`|${c}|`,
`(${c})^t`,
])
@@ -198,10 +198,10 @@ describe("constant proof boundaries", () => {
}
for (const expression of [
"0(1/0)",
- "0\\ln(-1)",
+ String.raw`0\ln(-1)`,
"0^0",
"0^{-1}",
- "\\sqrt[0]{2}",
+ String.raw`\sqrt[0]{2}`,
])
expect(
() =>
@@ -234,7 +234,7 @@ describe("constant proof boundaries", () => {
for (const [decimal, multiple] of roundedPi)
expect(
validateLaplacePfdAnswer(
- `e^{-4t}u((${decimal}-${multiple}\\pi)t)`,
+ String.raw`e^{-4t}u((${decimal}-${multiple}\pi)t)`,
problem,
).status,
).toBe("unsupported");
diff --git a/tests/unit/convolution-beginner-workflow.test.ts b/tests/unit/convolution-beginner-workflow.test.ts
index 5522868c..00e2beee 100644
--- a/tests/unit/convolution-beginner-workflow.test.ts
+++ b/tests/unit/convolution-beginner-workflow.test.ts
@@ -555,10 +555,10 @@ describe("convolution beginner workflow metadata", () => {
expect(parseConvolutionScalarInput("-inf")).toBe(
Number.NEGATIVE_INFINITY,
);
- expect(parseConvolutionScalarInput("\\infty")).toBe(
+ expect(parseConvolutionScalarInput(String.raw`\infty`)).toBe(
Number.POSITIVE_INFINITY,
);
- expect(parseConvolutionScalarInput("-\\infty")).toBe(
+ expect(parseConvolutionScalarInput(String.raw`-\infty`)).toBe(
Number.NEGATIVE_INFINITY,
);
expect(parseConvolutionScalarInput("∞")).toBe(Number.POSITIVE_INFINITY);
diff --git a/tests/unit/convolution-expression-validation.test.ts b/tests/unit/convolution-expression-validation.test.ts
index 227a0338..01cd4a6d 100644
--- a/tests/unit/convolution-expression-validation.test.ts
+++ b/tests/unit/convolution-expression-validation.test.ts
@@ -77,7 +77,10 @@ describe("convolution expression equivalence", () => {
/** Ambiguous exact constant proofs retain their more specific explanation. */
it("preserves a constant-verification diagnostic", () => {
expect(
- verifyConvolutionExpression("u((3.141592653589793-\\pi)t)", "0"),
+ verifyConvolutionExpression(
+ String.raw`u((3.141592653589793-\pi)t)`,
+ "0",
+ ),
).toEqual({
status: "unsupported",
message:
@@ -142,7 +145,9 @@ describe("convolution expression equivalence", () => {
expect(convolutionExpressionsMatch("t", "t", { min: 1, max: 1 })).toBe(
false,
);
- expect(convolutionExpressionsMatch("inf", "\\infty")).toBe(true);
+ expect(convolutionExpressionsMatch("inf", String.raw`\infty`)).toBe(
+ true,
+ );
});
/** Equivalent finite constants must use the same expression evaluator. */
it.each(["2+2", "(4)", "8/2", "4+t-t"])(
@@ -217,7 +222,9 @@ describe("convolution expression equivalence", () => {
});
/** Infinity is a scalar boundary sentinel rather than a finite expression. */
it("preserves infinity boundary matching and rejects invalid expressions", () => {
- expect(convolutionExpressionsMatch("inf", "\\infty")).toBe(true);
+ expect(convolutionExpressionsMatch("inf", String.raw`\infty`)).toBe(
+ true,
+ );
expect(convolutionExpressionsMatch("-inf", "inf")).toBe(false);
expect(convolutionExpressionsMatch("4", "5")).toBe(false);
expect(convolutionExpressionsMatch("1/0", "0")).toBe(false);
diff --git a/tests/unit/convolution-pulse-formatting.test.ts b/tests/unit/convolution-pulse-formatting.test.ts
index 1f01dd9c..b2885fc5 100644
--- a/tests/unit/convolution-pulse-formatting.test.ts
+++ b/tests/unit/convolution-pulse-formatting.test.ts
@@ -24,13 +24,17 @@ describe("convolution pulse formatting", () => {
});
it("simplifies unit and shifted-unit pulses while preserving general scaling", () => {
- expect(formatRectPulseLatex(1)).toBe("\\operatorname{rect}(t)");
- expect(formatRectPulseLatex(1, 2)).toBe("\\operatorname{rect}(t - 2)");
+ expect(formatRectPulseLatex(1)).toBe(
+ String.raw`\operatorname{rect}(t)`,
+ );
+ expect(formatRectPulseLatex(1, 2)).toBe(
+ String.raw`\operatorname{rect}(t - 2)`,
+ );
expect(formatRectPulseLatex(1, -2, -1)).toBe(
- "-\\operatorname{rect}(t + 2)",
+ String.raw`-\operatorname{rect}(t + 2)`,
);
expect(formatRectPulseLatex(3, 1, 2)).toBe(
- "2\\operatorname{rect}\\left(\\frac{t - 1}{3}\\right)",
+ String.raw`2\operatorname{rect}\left(\frac{t - 1}{3}\right)`,
);
});
diff --git a/tests/unit/convolution-step-solver-lifecycle.test.ts b/tests/unit/convolution-step-solver-lifecycle.test.ts
index 482aa576..26b1c9af 100644
--- a/tests/unit/convolution-step-solver-lifecycle.test.ts
+++ b/tests/unit/convolution-step-solver-lifecycle.test.ts
@@ -247,7 +247,7 @@ describe("ConvolutionStepSolverState lifecycle and regression tests", () => {
expect(parseConvolutionScalarInput("+inf")).toBe(
Number.POSITIVE_INFINITY,
);
- expect(parseConvolutionScalarInput("-\\infty")).toBe(
+ expect(parseConvolutionScalarInput(String.raw`-\infty`)).toBe(
Number.NEGATIVE_INFINITY,
);
});
@@ -879,7 +879,7 @@ describe("ConvolutionStepSolverState lifecycle and regression tests", () => {
};
const section = sections[0];
if (!section) throw new Error("Expected exponential section.");
- expect(section.leftLatex).toContain("\\infty");
+ expect(section.leftLatex).toContain(String.raw`\infty`);
const input = solver.step3.edgeInputs[section.id];
if (!input) throw new Error("Expected infinite edge input.");
for (const [answer, diagnostic] of [
diff --git a/tests/unit/convolution-symbolic-grading.test.ts b/tests/unit/convolution-symbolic-grading.test.ts
index 7d2d086c..c1f1392f 100644
--- a/tests/unit/convolution-symbolic-grading.test.ts
+++ b/tests/unit/convolution-symbolic-grading.test.ts
@@ -25,7 +25,9 @@ import {
* @returns Equivalent expression preserving infinity notation.
*/
function withZero(expression: string): string {
- return expression.includes("\\infty") ? expression : `(${expression})+0`;
+ return expression.includes(String.raw`\infty`)
+ ? expression
+ : `(${expression})+0`;
}
/**
@@ -170,7 +172,7 @@ function verifyBounds(
).toBe("valid");
}
const first = field.boundInputs[0];
- if (first && !first.lower.includes("\\infty")) {
+ if (first && !first.lower.includes(String.raw`\infty`)) {
field.stage = "bounds";
const original = first.lower;
first.lower = `(${original})+1`;
diff --git a/tests/unit/ctft-answer-validation.test.ts b/tests/unit/ctft-answer-validation.test.ts
index e07e895a..7f9210a1 100644
--- a/tests/unit/ctft-answer-validation.test.ts
+++ b/tests/unit/ctft-answer-validation.test.ts
@@ -50,7 +50,7 @@ describe("CTFT answer validation", () => {
validateCtftAnswer(`1+${product}`, problem).status,
product,
).toBe("unsupported");
- for (const term of [`0${d}`, `${d}-${d}`, `0${d}\\omega`])
+ for (const term of [`0${d}`, `${d}-${d}`, String.raw`0${d}\omega`])
expect(
validateCtftAnswer(`1+(${term})`, problem).status,
term,
diff --git a/tests/unit/ctft-presentation.test.ts b/tests/unit/ctft-presentation.test.ts
index 8df367d1..f4b87d6d 100644
--- a/tests/unit/ctft-presentation.test.ts
+++ b/tests/unit/ctft-presentation.test.ts
@@ -37,9 +37,9 @@ describe("exact CTFT solutions", () => {
/** Odd generated widths retain reduced fractions in bounds, phases, identities, and hints. */
it("formats pulse half-widths exactly throughout the lesson", () => {
for (const [T, half] of [
- [1, "\\frac{1}{2}"],
+ [1, String.raw`\frac{1}{2}`],
[2, "1"],
- [3, "\\frac{3}{2}"],
+ [3, String.raw`\frac{3}{2}`],
[4, "2"],
[6, "3"],
] as const) {
@@ -100,10 +100,10 @@ describe("exact CTFT solutions", () => {
if (task.kind === "location")
expect(value).toBe(String(location));
else {
- expect(value).toContain("\\pi");
+ expect(value).toContain(String.raw`\pi`);
if (stage.id === "final" && t0)
expect(value).toContain(`(${location})(${t0})`);
- else expect(value).toBe("\\pi");
+ else expect(value).toBe(String.raw`\pi`);
}
}
}
diff --git a/tests/unit/ctft-tutor.test.ts b/tests/unit/ctft-tutor.test.ts
index 80a79729..931e2351 100644
--- a/tests/unit/ctft-tutor.test.ts
+++ b/tests/unit/ctft-tutor.test.ts
@@ -78,7 +78,7 @@ function answerCurrent(solver: CtftStepSolverState, reverse = false): void {
solver.stages[stage.id]!.parts[
task.id.replace("weight", "location")
]!.input;
- state.input = `\\pi e^{-j(${location})(${stage.id === "base" ? 0 : solver.problem.params.t0})}`;
+ state.input = String.raw`\pi e^{-j(${location})(${stage.id === "base" ? 0 : solver.problem.params.t0})}`;
}
solver.check(stage.id, task.id);
expect(
@@ -283,7 +283,9 @@ describe("CTFT tutor", () => {
expect(task.hints.join(" ")).not.toMatch(
/verified endpoint|verified exponent|your sine expression|upper minus lower/,
);
- expect(task.identityLatex ?? "").not.toContain("\\int");
+ expect(task.identityLatex ?? "").not.toContain(
+ String.raw`\int`,
+ );
}
}
const derivation = buildCtftLesson(
@@ -384,12 +386,12 @@ describe("CTFT tutor", () => {
).toBe("unsupported");
for (const [answer, status] of [
["", "invalid"],
- ["\\frac{", "invalid"],
+ [String.raw`\frac{`, "invalid"],
["omega-omega+pi", "invalid"],
["0/0", "invalid"],
["tan(omega)", "unsupported"],
["delta(omega)", "unsupported"],
- ["\\delta(omega)", "invalid"],
+ [String.raw`\delta(omega)`, "invalid"],
] as const)
expect(
validateCtftImpulseRows(["-3", "3"], [answer, "pi"], problem)
@@ -463,7 +465,9 @@ describe("CTFT tutor", () => {
expect(validateCtftCalculation(answer, target).status).toBe(
"incorrect",
);
- expect(validateCtftCalculation("\\frac{", "1").status).toBe("invalid");
+ expect(validateCtftCalculation(String.raw`\frac{`, "1").status).toBe(
+ "invalid",
+ );
expect(validateCtftCalculation("sin(omega^2)", "1").status).toBe(
"unsupported",
);
@@ -603,9 +607,11 @@ describe("CTFT tutor", () => {
expect(validateCtftConstant("2+omega-omega", "2", true).status).toBe(
"invalid",
);
- expect(validateCtftConstant("\\pi", "\\pi").status).toBe("correct");
+ expect(
+ validateCtftConstant(String.raw`\pi`, String.raw`\pi`).status,
+ ).toBe("correct");
expect(validateCtftConstant("1/0", "2").status).toBe("invalid");
- expect(validateCtftConstant("\\tan(omega)", "2").status).toBe(
+ expect(validateCtftConstant(String.raw`\tan(omega)`, "2").status).toBe(
"unsupported",
);
expect(validateCtftConstant("x".repeat(16385), "2").status).toBe(
@@ -621,7 +627,7 @@ describe("CTFT tutor", () => {
advance(solver, "base");
for (const [input, expected] of [
["", "invalid"],
- ["\\tan(omega)", "unsupported"],
+ [String.raw`\tan(omega)`, "unsupported"],
["sinc(2omega/pi)", "incorrect"],
]) {
solver.currentStepState!.input = input!;
diff --git a/tests/unit/evaluator.test.ts b/tests/unit/evaluator.test.ts
index 29c1d196..e1e4f464 100644
--- a/tests/unit/evaluator.test.ts
+++ b/tests/unit/evaluator.test.ts
@@ -198,7 +198,7 @@ describe("Math Engine Evaluator (evaluator.ts)", () => {
expect(shiftedVal).toBeCloseTo(3 * Math.exp(-2), 4);
});
- it("evaluates fractions formatted with \\frac", () => {
+ it(String.raw`evaluates fractions formatted with \frac`, () => {
const val = evaluateLatexAt(
String.raw`\frac{3}{4} t + \frac{1}{2}`,
2,
@@ -300,12 +300,15 @@ describe("Math Engine Evaluator (evaluator.ts)", () => {
expect(evaluatePiecewiseLatexAt(piecewise, 3)).toBe(6);
});
- it("evaluates piecewise interval expressions with \\text{for} syntax", () => {
- const piecewise = String.raw`\begin{cases} 0 \quad \text{for} \quad t < 0 \\ 3t \quad \text{for} \quad 0 \le t < 2 \\ 6 \quad \text{for} \quad t \ge 2 \end{cases}`;
- expect(evaluatePiecewiseLatexAt(piecewise, -1)).toBe(0);
- expect(evaluatePiecewiseLatexAt(piecewise, 1)).toBe(3);
- expect(evaluatePiecewiseLatexAt(piecewise, 4)).toBe(6);
- });
+ it(
+ String.raw`evaluates piecewise interval expressions with \text{for} syntax`,
+ () => {
+ const piecewise = String.raw`\begin{cases} 0 \quad \text{for} \quad t < 0 \\ 3t \quad \text{for} \quad 0 \le t < 2 \\ 6 \quad \text{for} \quad t \ge 2 \end{cases}`;
+ expect(evaluatePiecewiseLatexAt(piecewise, -1)).toBe(0);
+ expect(evaluatePiecewiseLatexAt(piecewise, 1)).toBe(3);
+ expect(evaluatePiecewiseLatexAt(piecewise, 4)).toBe(6);
+ },
+ );
it("returns 0 when sample point does not match any piecewise interval condition", () => {
const piecewise = String.raw`\begin{cases} 2t, & 1 \le t \le 2 \end{cases}`;
diff --git a/tests/unit/formatting.test.ts b/tests/unit/formatting.test.ts
index d4788b34..5b63524e 100644
--- a/tests/unit/formatting.test.ts
+++ b/tests/unit/formatting.test.ts
@@ -16,12 +16,12 @@ describe("formatCoefficientTerm", () => {
it("omits unit coefficient 1 for non-empty symbols", () => {
expect(formatCoefficientTerm(1, "y(t)", false)).toBe("+ y(t)");
expect(formatCoefficientTerm(1, "y(t)", true)).toBe("y(t)");
- expect(formatCoefficientTerm(1, "\\frac{dy}{dt}", false)).toBe(
- "+ \\frac{dy}{dt}",
- );
- expect(formatCoefficientTerm(1, "\\frac{d^2 y}{dt^2}", true)).toBe(
- "\\frac{d^2 y}{dt^2}",
+ expect(formatCoefficientTerm(1, String.raw`\frac{dy}{dt}`, false)).toBe(
+ String.raw`+ \frac{dy}{dt}`,
);
+ expect(
+ formatCoefficientTerm(1, String.raw`\frac{d^2 y}{dt^2}`, true),
+ ).toBe(String.raw`\frac{d^2 y}{dt^2}`);
expect(formatCoefficientTerm(1, "s", false)).toBe("+ s");
expect(formatCoefficientTerm(1, "s", true)).toBe("s");
});
@@ -29,9 +29,9 @@ describe("formatCoefficientTerm", () => {
it("omits unit coefficient -1 for non-empty symbols with correct negative sign", () => {
expect(formatCoefficientTerm(-1, "y(t)", false)).toBe("- y(t)");
expect(formatCoefficientTerm(-1, "y(t)", true)).toBe("-y(t)");
- expect(formatCoefficientTerm(-1, "\\frac{dy}{dt}", false)).toBe(
- "- \\frac{dy}{dt}",
- );
+ expect(
+ formatCoefficientTerm(-1, String.raw`\frac{dy}{dt}`, false),
+ ).toBe(String.raw`- \frac{dy}{dt}`);
expect(formatCoefficientTerm(-1, "s", false)).toBe("- s");
expect(formatCoefficientTerm(-1, "s", true)).toBe("-s");
});
@@ -39,11 +39,11 @@ describe("formatCoefficientTerm", () => {
it("includes numerical coefficient for values not equal to +/- 1", () => {
expect(formatCoefficientTerm(2, "y(t)", false)).toBe("+ 2 y(t)");
expect(formatCoefficientTerm(2, "y(t)", true)).toBe("2 y(t)");
- expect(formatCoefficientTerm(-3, "\\frac{dy}{dt}", false)).toBe(
- "- 3 \\frac{dy}{dt}",
- );
- expect(formatCoefficientTerm(-3, "\\frac{dy}{dt}", true)).toBe(
- "-3 \\frac{dy}{dt}",
+ expect(
+ formatCoefficientTerm(-3, String.raw`\frac{dy}{dt}`, false),
+ ).toBe(String.raw`- 3 \frac{dy}{dt}`);
+ expect(formatCoefficientTerm(-3, String.raw`\frac{dy}{dt}`, true)).toBe(
+ String.raw`-3 \frac{dy}{dt}`,
);
expect(formatCoefficientTerm(4, "s", false)).toBe("+ 4 s");
});
@@ -146,16 +146,16 @@ describe("formatQuadraticPolynomial", () => {
describe("formatOdeLhs", () => {
it("formats ODE left-hand side omitting unit 1 and -1 coefficients", () => {
expect(formatOdeLhs(1, 2, 1)).toBe(
- "\\frac{d^2 y}{dt^2} + 2 \\frac{dy}{dt} + y(t)",
+ String.raw`\frac{d^2 y}{dt^2} + 2 \frac{dy}{dt} + y(t)`,
);
expect(formatOdeLhs(1, 1, 1)).toBe(
- "\\frac{d^2 y}{dt^2} + \\frac{dy}{dt} + y(t)",
+ String.raw`\frac{d^2 y}{dt^2} + \frac{dy}{dt} + y(t)`,
);
expect(formatOdeLhs(1, -1, -1)).toBe(
- "\\frac{d^2 y}{dt^2} - \\frac{dy}{dt} - y(t)",
+ String.raw`\frac{d^2 y}{dt^2} - \frac{dy}{dt} - y(t)`,
);
expect(formatOdeLhs(1, 3, 2)).toBe(
- "\\frac{d^2 y}{dt^2} + 3 \\frac{dy}{dt} + 2 y(t)",
+ String.raw`\frac{d^2 y}{dt^2} + 3 \frac{dy}{dt} + 2 y(t)`,
);
});
});
@@ -184,9 +184,9 @@ describe("formatRootFactor", () => {
describe("sanitizeLatexMath", () => {
it("replaces adjacent double operators (+ +, + -, - -, - +)", () => {
- expect(sanitizeLatexMath("2e^{-t} + + \\frac{1}{2}\\sin(2t)")).toBe(
- "2e^{-t} + \\frac{1}{2}\\sin(2t)",
- );
+ expect(
+ sanitizeLatexMath(String.raw`2e^{-t} + + \frac{1}{2}\sin(2t)`),
+ ).toBe(String.raw`2e^{-t} + \frac{1}{2}\sin(2t)`);
expect(sanitizeLatexMath("C_1 e^{-t} + - 3 e^{-2t}")).toBe(
"C_1 e^{-t} - 3 e^{-2t}",
);
@@ -199,8 +199,8 @@ describe("sanitizeLatexMath", () => {
it("cleans unit multipliers and leading positive signs inside brackets", () => {
expect(sanitizeLatexMath("e^{(-1t)}")).toBe("e^{-t}");
expect(sanitizeLatexMath("e^{(1t)}")).toBe("e^{t}");
- expect(sanitizeLatexMath("[ + 2\\cos(t) - 3\\sin(t)]")).toBe(
- "[2\\cos(t) - 3\\sin(t)]",
+ expect(sanitizeLatexMath(String.raw`[ + 2\cos(t) - 3\sin(t)]`)).toBe(
+ String.raw`[2\cos(t) - 3\sin(t)]`,
);
});
});
@@ -276,9 +276,15 @@ describe("sanitizeUnitCoefficients", () => {
expect(sanitizeUnitCoefficients("1e^{-1t}")).toBe("e^{-t}");
expect(sanitizeUnitCoefficients("-1e^{-1t}")).toBe("-e^{-t}");
expect(sanitizeUnitCoefficients("1e^{1t}")).toBe("e^{t}");
- expect(sanitizeUnitCoefficients("1\\cos(1t)")).toBe("\\cos(t)");
- expect(sanitizeUnitCoefficients("1\\sin(-1t)")).toBe("\\sin(-t)");
- expect(sanitizeUnitCoefficients("-1\\cos(2t)")).toBe("-\\cos(2t)");
+ expect(sanitizeUnitCoefficients(String.raw`1\cos(1t)`)).toBe(
+ String.raw`\cos(t)`,
+ );
+ expect(sanitizeUnitCoefficients(String.raw`1\sin(-1t)`)).toBe(
+ String.raw`\sin(-t)`,
+ );
+ expect(sanitizeUnitCoefficients(String.raw`-1\cos(2t)`)).toBe(
+ String.raw`-\cos(2t)`,
+ );
});
it("handles Electrical Engineering imaginary unit j notation", () => {
@@ -290,7 +296,9 @@ describe("sanitizeUnitCoefficients", () => {
expect(sanitizeUnitCoefficients("-1j")).toBe("-j");
expect(sanitizeUnitCoefficients("j1e^{-j1t}")).toBe("je^{-jt}");
expect(sanitizeUnitCoefficients("1je^{-1jt}")).toBe("je^{-jt}");
- expect(sanitizeUnitCoefficients("\\pm j1")).toBe("\\pm j");
+ expect(sanitizeUnitCoefficients(String.raw`\pm j1`)).toBe(
+ String.raw`\pm j`,
+ );
});
it("reduces nested double parentheses", () => {
@@ -351,10 +359,18 @@ describe("sanitizeUnitCoefficients", () => {
expect(sanitizeUnitCoefficients("s + 1 = 0")).toBe("s + 1 = 0");
expect(sanitizeUnitCoefficients("y(0) = 1")).toBe("y(0) = 1");
expect(sanitizeUnitCoefficients("5 + 1")).toBe("5 + 1");
- expect(sanitizeUnitCoefficients("\\frac{1}{2}")).toBe("\\frac{1}{2}");
- expect(sanitizeUnitCoefficients("\\frac{1}{10}")).toBe("\\frac{1}{10}");
- expect(sanitizeUnitCoefficients("\\cos(10t)")).toBe("\\cos(10t)");
- expect(sanitizeUnitCoefficients("\\sin(151t)")).toBe("\\sin(151t)");
+ expect(sanitizeUnitCoefficients(String.raw`\frac{1}{2}`)).toBe(
+ String.raw`\frac{1}{2}`,
+ );
+ expect(sanitizeUnitCoefficients(String.raw`\frac{1}{10}`)).toBe(
+ String.raw`\frac{1}{10}`,
+ );
+ expect(sanitizeUnitCoefficients(String.raw`\cos(10t)`)).toBe(
+ String.raw`\cos(10t)`,
+ );
+ expect(sanitizeUnitCoefficients(String.raw`\sin(151t)`)).toBe(
+ String.raw`\sin(151t)`,
+ );
expect(sanitizeUnitCoefficients("100")).toBe("100");
});
});
diff --git a/tests/unit/fourier-expression-oracle.ts b/tests/unit/fourier-expression-oracle.ts
index b5ede860..f34628a4 100644
--- a/tests/unit/fourier-expression-oracle.ts
+++ b/tests/unit/fourier-expression-oracle.ts
@@ -207,8 +207,8 @@ export function sampleFourierExpression(
sample: Sample,
): Complex {
const normalized = latex
- .replaceAll("\\left[", "\\left(")
- .replaceAll("\\right]", "\\right)");
+ .replaceAll(String.raw`\left[`, String.raw`\left(`)
+ .replaceAll(String.raw`\right]`, String.raw`\right)`);
return evaluate(parseStrictLatex(normalized), sample);
}
@@ -222,11 +222,11 @@ export function sampleFourierDefinition(
latex: string,
sample: Sample,
): Complex {
- if (!latex.startsWith("\\begin{cases}"))
+ if (!latex.startsWith(String.raw`\begin{cases}`))
return sampleFourierExpression(latex, sample);
const rows = latex
- .replace("\\begin{cases}", "")
- .replace("\\end{cases}", "")
+ .replace(String.raw`\begin{cases}`, "")
+ .replace(String.raw`\end{cases}`, "")
.split("\\\\");
for (const row of rows) {
const [value, condition = ""] = row.split("&");
diff --git a/tests/unit/fourier-series-distractor-regressions.test.ts b/tests/unit/fourier-series-distractor-regressions.test.ts
index 04a71c4f..f813bfca 100644
--- a/tests/unit/fourier-series-distractor-regressions.test.ts
+++ b/tests/unit/fourier-series-distractor-regressions.test.ts
@@ -123,8 +123,9 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
const witnesses = options.map((option) =>
[0.13, 0.37, 0.81].map((fraction) => {
const t = fraction * coeffs.T0;
- const synthesis =
- option.latex.split(",\\qquad")[0]!;
+ const synthesis = option.latex.split(
+ String.raw`,\qquad`,
+ )[0]!;
const rhs = synthesis.slice(
synthesis.indexOf("=") + 1,
);
diff --git a/tests/unit/fourier-series-its-generator.test.ts b/tests/unit/fourier-series-its-generator.test.ts
index 6e09adc9..b84548c4 100644
--- a/tests/unit/fourier-series-its-generator.test.ts
+++ b/tests/unit/fourier-series-its-generator.test.ts
@@ -20,15 +20,15 @@ describe("Fourier Series ITS Step Generator Engine", () => {
] as const;
it.each([
- ["square", "4(1)", "\\sin"],
- ["square_odd", "4(1)", "\\sin"],
- ["square_even", "\\sin\\left(\\frac{n\\pi}{2}", "\\cos"],
- ["triangle", "8(1)", "n^2\\pi^2"],
- ["triangle_odd", "8(1)", "\\sin\\left(\\frac{n\\pi}{2}"],
- ["triangle_even", "8(1)", "n^2\\pi^2"],
+ ["square", "4(1)", String.raw`\sin`],
+ ["square_odd", "4(1)", String.raw`\sin`],
+ ["square_even", String.raw`\sin\left(\frac{n\pi}{2}`, String.raw`\cos`],
+ ["triangle", "8(1)", String.raw`n^2\pi^2`],
+ ["triangle_odd", "8(1)", String.raw`\sin\left(\frac{n\pi}{2}`],
+ ["triangle_even", "8(1)", String.raw`n^2\pi^2`],
["sawtooth", "(-1)^{n+1}", "2(1)"],
["half_wave_sine", "F_n", "n=-1"],
- ["full_wave_sine", "4n^2-1", "\\frac{2(1)}{\\pi}"],
+ ["full_wave_sine", "4n^2-1", String.raw`\frac{2(1)}{\pi}`],
] as const)(
"builds the exact final series for %s",
(waveform, expectedA, expectedB) => {
@@ -197,7 +197,7 @@ describe("Fourier Series ITS Step Generator Engine", () => {
}
const compact = problem.conversionChallenge.parts[1].resultLatex;
expect(compact).toContain("c_n");
- expect(compact).toContain("\\theta_n");
+ expect(compact).toContain(String.raw`\theta_n`);
expect(compact).not.toContain("A_n");
},
);
diff --git a/tests/unit/fourier-series-math-contracts.test.ts b/tests/unit/fourier-series-math-contracts.test.ts
index 3dbb7fac..bb684ff2 100644
--- a/tests/unit/fourier-series-math-contracts.test.ts
+++ b/tests/unit/fourier-series-math-contracts.test.ts
@@ -36,7 +36,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
});
const d = buildFourierSeriesSymbolicDerivation(
coeffs,
- "\\pi/2",
+ String.raw`\pi/2`,
);
const latex = d.expEvaluationLatex!;
/** Confirms scientific parameters also remain valid in the rendered worked evaluation. */
@@ -54,7 +54,9 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
`${n === 1 ? "F_1" : "F_{-1}"}=`,
)[1]!
.split("\\\\")[0]!
- : latex.split("F_n=")[1]!.split("\\quad")[0]!;
+ : latex
+ .split("F_n=")[1]!
+ .split(String.raw`\quad`)[0]!;
const displayed = sampleFourierBoundaryExpression(
row.split("=")[0]!,
sample,
@@ -79,7 +81,10 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
A: 3,
T0: 4,
});
- const d = buildFourierSeriesSymbolicDerivation(coeffs, "\\pi/2");
+ const d = buildFourierSeriesSymbolicDerivation(
+ coeffs,
+ String.raw`\pi/2`,
+ );
for (const n of [1, 2, 3]) {
for (const [label, integral, expected] of [
["a_0", d.a0IntegralLatex, coeffs.a0],
@@ -103,7 +108,10 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
A: 2,
T0: 4,
});
- const d = buildFourierSeriesSymbolicDerivation(coeffs, "\\pi/2");
+ const d = buildFourierSeriesSymbolicDerivation(
+ coeffs,
+ String.raw`\pi/2`,
+ );
for (const n of [-5, -2, -1, 0, 1, 2, 5]) {
let re = 0;
let im = 0;
@@ -141,7 +149,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
A: 3,
T0: 4,
});
- const compact = buildCompactSeriesLatex(coeffs, "\\pi/2");
+ const compact = buildCompactSeriesLatex(coeffs, String.raw`\pi/2`);
for (const n of [1, 2, 3, 4, 5, 7]) {
let amplitude: string;
let phase: string;
@@ -162,7 +170,7 @@ describe.each(FOURIER_SERIES_WAVEFORM_TYPES)(
/c_n=(.*?),\\quad \\theta_n=/,
)![1]!;
phase = compact
- .split("\\theta_n=")[1]!
+ .split(String.raw`\theta_n=`)[1]!
.replace(/\\ \(n\\text\{ odd\}\)$/, "");
}
const sample = { coeffs, n, t: 0 };
diff --git a/tests/unit/fourier-series-review-regressions.test.ts b/tests/unit/fourier-series-review-regressions.test.ts
index ae5a33b2..490e31bd 100644
--- a/tests/unit/fourier-series-review-regressions.test.ts
+++ b/tests/unit/fourier-series-review-regressions.test.ts
@@ -99,9 +99,11 @@ describe("Fourier Series adversarial regressions", () => {
).toBeCloseTo(expected, 2);
}
if (T0 !== 2 && T0 !== 4) {
- expect(problem.omega0Latex).toContain(`\\frac{2\\pi}{${T0}}`);
+ expect(problem.omega0Latex).toContain(
+ String.raw`\frac{2\pi}{${T0}}`,
+ );
expect(problem.itsData.step1.hints[2]).toContain(
- `\\frac{2\\pi}{${T0}}`,
+ String.raw`\frac{2\pi}{${T0}}`,
);
}
},
diff --git a/tests/unit/fourier-series-step-solver.test.ts b/tests/unit/fourier-series-step-solver.test.ts
index 285d577d..27ede942 100644
--- a/tests/unit/fourier-series-step-solver.test.ts
+++ b/tests/unit/fourier-series-step-solver.test.ts
@@ -79,14 +79,22 @@ describe("FourierSeriesStepSolverState Reactive Controller", () => {
input: { period: "0.000104", periodUnit: "ms" },
accepted: true,
},
- { T0: 1e21, input: { freq: "6.5\\times10^{-21}" }, accepted: true },
{
T0: 1e21,
- input: { freq: "1.04\\times10^{-21}", freqUnit: "Hz" },
+ input: { freq: String.raw`6.5\times10^{-21}` },
+ accepted: true,
+ },
+ {
+ T0: 1e21,
+ input: { freq: String.raw`1.04\times10^{-21}`, freqUnit: "Hz" },
accepted: true,
},
{ T0: 1e-7, input: { period: "0.000000106" }, accepted: false },
- { T0: 1e21, input: { freq: "6.7\\times10^{-21}" }, accepted: false },
+ {
+ T0: 1e21,
+ input: { freq: String.raw`6.7\times10^{-21}` },
+ accepted: false,
+ },
{ T0: 2, input: { period: "2.06" }, accepted: false },
{ T0: 2, input: { freq: String(Math.PI + 0.06) }, accepted: false },
{ T0: 2, input: { period: "2.04", freq: "3.18" }, accepted: true },
@@ -564,7 +572,7 @@ describe("FourierSeriesStepSolverState Reactive Controller", () => {
expect(opt.latex.length).toBeGreaterThan(0);
expect(
opt.latex.includes("=") ||
- opt.latex.includes("\\int") ||
+ opt.latex.includes(String.raw`\int`) ||
opt.latex.includes("0"),
).toBe(true);
}
diff --git a/tests/unit/fourier-series-symbolic-derivations.test.ts b/tests/unit/fourier-series-symbolic-derivations.test.ts
index 0990ab05..8c03cca6 100644
--- a/tests/unit/fourier-series-symbolic-derivations.test.ts
+++ b/tests/unit/fourier-series-symbolic-derivations.test.ts
@@ -36,9 +36,12 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
A: 3,
T0: 4,
});
- const latex = buildFinalSeriesLatex(coeffs, "\\frac{\\pi}{2}");
+ const latex = buildFinalSeriesLatex(
+ coeffs,
+ String.raw`\frac{\pi}{2}`,
+ );
expect(latex).toContain("x(t) =");
- expect(latex).toContain("\\frac{\\pi}{2}");
+ expect(latex).toContain(String.raw`\frac{\pi}{2}`);
},
);
@@ -49,7 +52,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
T0: 2,
} as FourierSeriesCoefficients;
expect(() =>
- buildFinalSeriesLatex(invalidCoeffs, "\\pi"),
+ buildFinalSeriesLatex(invalidCoeffs, String.raw`\pi`),
).toThrowError(/Unsupported waveform type/);
});
});
@@ -62,8 +65,13 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
A: 2,
T0: 2,
});
- const compactLatex = buildCompactSeriesLatex(coeffs, "\\pi");
- expect(compactLatex).toContain("x(t)=\\frac{c_0}{2}+\\sum");
+ const compactLatex = buildCompactSeriesLatex(
+ coeffs,
+ String.raw`\pi`,
+ );
+ expect(compactLatex).toContain(
+ String.raw`x(t)=\frac{c_0}{2}+\sum`,
+ );
expect(compactLatex).toContain("c_n=");
},
);
@@ -75,7 +83,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
T0: 2,
} as FourierSeriesCoefficients;
expect(() =>
- buildCompactSeriesLatex(invalidCoeffs, "\\pi"),
+ buildCompactSeriesLatex(invalidCoeffs, String.raw`\pi`),
).toThrowError(/Unsupported waveform type/);
});
});
@@ -106,7 +114,7 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
});
const derivation = buildFourierSeriesSymbolicDerivation(
coeffs,
- "\\pi",
+ String.raw`\pi`,
);
expect(derivation.a0Latex).toBeDefined();
@@ -114,7 +122,9 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
expect(derivation.bnLatex).toBeDefined();
expect(derivation.FnLatex).toBeDefined();
expect(derivation.finalTrigLatex).toContain("x(t) =");
- expect(derivation.finalExpLatex).toContain("x(t)=\\sum");
+ expect(derivation.finalExpLatex).toContain(
+ String.raw`x(t)=\sum`,
+ );
expect(derivation.a0IntegralLatex).toContain("a_0=");
expect(derivation.evaluationLatex).toBeDefined();
},
@@ -127,7 +137,10 @@ describe("Fourier Series Symbolic Derivations & LaTeX Templates", () => {
T0: 2,
} as FourierSeriesCoefficients;
expect(() =>
- buildFourierSeriesSymbolicDerivation(invalidCoeffs, "\\pi"),
+ buildFourierSeriesSymbolicDerivation(
+ invalidCoeffs,
+ String.raw`\pi`,
+ ),
).toThrowError(/Unsupported waveform type/);
});
});
diff --git a/tests/unit/fourier-series-tutor-contracts.test.ts b/tests/unit/fourier-series-tutor-contracts.test.ts
index 246fc18c..ddbea855 100644
--- a/tests/unit/fourier-series-tutor-contracts.test.ts
+++ b/tests/unit/fourier-series-tutor-contracts.test.ts
@@ -19,7 +19,7 @@ describe("Fourier tutor contracts", () => {
});
const derivation = buildFourierSeriesSymbolicDerivation(
problem.coeffs,
- "\\pi",
+ String.raw`\pi`,
);
delete derivation.expEvaluationLatex;
const step = buildStep6Data("exp", "even", derivation, Math.random);
@@ -49,6 +49,21 @@ describe("Fourier tutor contracts", () => {
expect(p.itsData.step3.hints.join(" ")).toContain("a_{2k}");
});
+ /** Ensures the no-parity explanation closes both LaTeX text groups. */
+ it("renders the half-wave-sine symmetry explanation", () => {
+ const problem = generateFourierSeriesProblem("half_wave_sine", {
+ seed: 1,
+ });
+ const latex = problem.solutionSteps[1]!.latex!;
+
+ expect(latex).toContain(
+ String.raw`a_n\text{ and }b_n\text{ must both be evaluated}`,
+ );
+ expect(() =>
+ renderToString(latex, { throwOnError: true }),
+ ).not.toThrow();
+ });
+
/** Tests both explicit paths even when they differ from the symmetry recommendation. */
it.each(["trig", "exp"] as const)(
"keeps assigned %s metadata and solution consistent",
diff --git a/tests/unit/fourier-transform-bank.test.ts b/tests/unit/fourier-transform-bank.test.ts
index ca65151c..7c9ba36a 100644
--- a/tests/unit/fourier-transform-bank.test.ts
+++ b/tests/unit/fourier-transform-bank.test.ts
@@ -6,14 +6,21 @@ describe("CTFT Problem Bank (fourier-transform-bank.ts)", () => {
expect(CTFT_EXAM_BANK.length).toBeGreaterThan(0);
});
- it("should enforce \\operatorname for all custom operators across all bank questions", () => {
- for (const item of CTFT_EXAM_BANK) {
- expect(item.promptLatex).not.toContain("\\text{sinc}");
- expect(item.promptLatex).not.toContain("\\text{rect}");
- expect(item.referenceAnswerLatex).not.toContain("\\text{sinc}");
- expect(item.referenceAnswerLatex).not.toContain("\\text{rect}");
- }
- });
+ it(
+ String.raw`should enforce \operatorname for all custom operators across all bank questions`,
+ () => {
+ for (const item of CTFT_EXAM_BANK) {
+ expect(item.promptLatex).not.toContain(String.raw`\text{sinc}`);
+ expect(item.promptLatex).not.toContain(String.raw`\text{rect}`);
+ expect(item.referenceAnswerLatex).not.toContain(
+ String.raw`\text{sinc}`,
+ );
+ expect(item.referenceAnswerLatex).not.toContain(
+ String.raw`\text{rect}`,
+ );
+ }
+ },
+ );
it("should provide multi-step solution breakdowns for every bank problem", () => {
for (const item of CTFT_EXAM_BANK) {
diff --git a/tests/unit/fourier-transform.test.ts b/tests/unit/fourier-transform.test.ts
index 55240acc..1fef49c6 100644
--- a/tests/unit/fourier-transform.test.ts
+++ b/tests/unit/fourier-transform.test.ts
@@ -34,17 +34,24 @@ describe("CTFT Math Engine (fourier-transform/index.ts)", () => {
}
});
describe("CTFT Transform Pairs & Custom Operator Formatting", () => {
- it("should evaluate rectangular pulse transform to normalized sinc with \\operatorname{sinc}", () => {
- const pair = getCtftPairLatex("rect", { T: 2 });
- expect(pair.timeLatex).toContain("\\operatorname{rect}");
- expect(pair.freqLatex).toContain("\\operatorname{sinc}");
- expect(pair.freqLatex).not.toContain("\\text{sinc}");
- });
+ it(
+ String.raw`should evaluate rectangular pulse transform to normalized sinc with \operatorname{sinc}`,
+ () => {
+ const pair = getCtftPairLatex("rect", { T: 2 });
+ expect(pair.timeLatex).toContain(
+ String.raw`\operatorname{rect}`,
+ );
+ expect(pair.freqLatex).toContain(
+ String.raw`\operatorname{sinc}`,
+ );
+ expect(pair.freqLatex).not.toContain(String.raw`\text{sinc}`);
+ },
+ );
it("should format exponential decay e^{-a t} u(t) correctly", () => {
const pair = getCtftPairLatex("exponential", { a: 3 });
expect(pair.timeLatex).toBe("e^{-3 t} u(t)");
- expect(pair.freqLatex).toBe("\\frac{1}{3 + j\\omega}");
+ expect(pair.freqLatex).toBe(String.raw`\frac{1}{3 + j\omega}`);
});
});
diff --git a/tests/unit/fraction.test.ts b/tests/unit/fraction.test.ts
index eba1e476..053ee1af 100644
--- a/tests/unit/fraction.test.ts
+++ b/tests/unit/fraction.test.ts
@@ -9,23 +9,23 @@ describe("toFractionLatex", () => {
});
it("formats standard repeating fractions correctly", () => {
- expect(toFractionLatex(1 / 3)).toBe("\\frac{1}{3}");
- expect(toFractionLatex(-1 / 3)).toBe("-\\frac{1}{3}");
- expect(toFractionLatex(1 / 6)).toBe("\\frac{1}{6}");
- expect(toFractionLatex(-7 / 6)).toBe("-\\frac{7}{6}");
+ expect(toFractionLatex(1 / 3)).toBe(String.raw`\frac{1}{3}`);
+ expect(toFractionLatex(-1 / 3)).toBe(String.raw`-\frac{1}{3}`);
+ expect(toFractionLatex(1 / 6)).toBe(String.raw`\frac{1}{6}`);
+ expect(toFractionLatex(-7 / 6)).toBe(String.raw`-\frac{7}{6}`);
});
it("formats ninths fractions correctly (1/9, 3/9, 10/9)", () => {
- expect(toFractionLatex(1 / 9)).toBe("\\frac{1}{9}");
- expect(toFractionLatex(3 / 9)).toBe("\\frac{1}{3}");
- expect(toFractionLatex(10 / 9)).toBe("\\frac{10}{9}");
- expect(toFractionLatex(-10 / 9)).toBe("-\\frac{10}{9}");
+ expect(toFractionLatex(1 / 9)).toBe(String.raw`\frac{1}{9}`);
+ expect(toFractionLatex(3 / 9)).toBe(String.raw`\frac{1}{3}`);
+ expect(toFractionLatex(10 / 9)).toBe(String.raw`\frac{10}{9}`);
+ expect(toFractionLatex(-10 / 9)).toBe(String.raw`-\frac{10}{9}`);
});
it("formats decimal fractions like 0.25, 0.75, -1.5", () => {
- expect(toFractionLatex(0.25)).toBe("\\frac{1}{4}");
- expect(toFractionLatex(0.75)).toBe("\\frac{3}{4}");
- expect(toFractionLatex(-1.5)).toBe("-\\frac{3}{2}");
+ expect(toFractionLatex(0.25)).toBe(String.raw`\frac{1}{4}`);
+ expect(toFractionLatex(0.75)).toBe(String.raw`\frac{3}{4}`);
+ expect(toFractionLatex(-1.5)).toBe(String.raw`-\frac{3}{2}`);
});
});
@@ -68,11 +68,17 @@ describe("parseNumericInput", () => {
});
it("parses LaTeX fraction notation", () => {
- expect(parseNumericInput("\\frac{5}{3}")).toBeCloseTo(5 / 3);
- expect(parseNumericInput("-\\frac{11}{3}")).toBeCloseTo(-11 / 3);
- expect(parseNumericInput("\\frac{-11}{3}")).toBeCloseTo(-11 / 3);
- expect(parseNumericInput("\\frac{11}{-3}")).toBeCloseTo(-11 / 3);
- expect(parseNumericInput("\\frac{-5}{-9}")).toBeCloseTo(5 / 9);
+ expect(parseNumericInput(String.raw`\frac{5}{3}`)).toBeCloseTo(5 / 3);
+ expect(parseNumericInput(String.raw`-\frac{11}{3}`)).toBeCloseTo(
+ -11 / 3,
+ );
+ expect(parseNumericInput(String.raw`\frac{-11}{3}`)).toBeCloseTo(
+ -11 / 3,
+ );
+ expect(parseNumericInput(String.raw`\frac{11}{-3}`)).toBeCloseTo(
+ -11 / 3,
+ );
+ expect(parseNumericInput(String.raw`\frac{-5}{-9}`)).toBeCloseTo(5 / 9);
});
it("returns NaN for invalid or empty inputs", () => {
diff --git a/tests/unit/input-builders.test.ts b/tests/unit/input-builders.test.ts
index b66b4a72..927dbce1 100644
--- a/tests/unit/input-builders.test.ts
+++ b/tests/unit/input-builders.test.ts
@@ -22,7 +22,7 @@ describe("Guided Form Builder LaTeX Validation Integration", () => {
*/
it("validates synthesized Laplace rational transfer function H(s)", () => {
// Synthesized from PoleZeroInput: \frac{2(s+1)}{(s+2)(s+3)}
- const synthesizedLatex = "\\frac{2(s+1)}{(s+2)(s+3)}";
+ const synthesizedLatex = String.raw`\frac{2(s+1)}{(s+2)(s+3)}`;
const refEval = (s: number): number => {
return (2 * (s + 1)) / ((s + 2) * (s + 3));
};
@@ -36,7 +36,7 @@ describe("Guided Form Builder LaTeX Validation Integration", () => {
*/
it("validates synthesized time-domain phasor sinusoid", () => {
// Synthesized from PhasorInput: 10 \cos(2t)
- const synthesizedLatex = "10 \\cos(2t)";
+ const synthesizedLatex = String.raw`10 \cos(2t)`;
const refEval = (t: number): number => 10 * Math.cos(2 * t);
const result = validateLatexAnswer(synthesizedLatex, refEval);
@@ -48,10 +48,9 @@ describe("Guided Form Builder LaTeX Validation Integration", () => {
*/
it("validates synthesized Fourier series coefficient expression", () => {
// Synthesized from FourierSeriesInput: \sum_{n=1}^{\infty} \left[ \frac{2}{n\pi} (1 - (-1)^n) \sin(n \omega_0 t) \right]
- const synthesizedLatex =
- "\\sum_{n=1}^{\\infty} \\left[ \\frac{2}{n\\pi} (1 - (-1)^n) \\sin(n \\pi t) \\right]";
+ const synthesizedLatex = String.raw`\sum_{n=1}^{\infty} \left[ \frac{2}{n\pi} (1 - (-1)^n) \sin(n \pi t) \right]`;
- expect(synthesizedLatex).toContain("\\frac{2}{n\\pi}");
+ expect(synthesizedLatex).toContain(String.raw`\frac{2}{n\pi}`);
expect(synthesizedLatex).toContain("(1 - (-1)^n)");
});
});
diff --git a/tests/unit/laplace-algebra.test.ts b/tests/unit/laplace-algebra.test.ts
index 0da136ea..56c4d6e3 100644
--- a/tests/unit/laplace-algebra.test.ts
+++ b/tests/unit/laplace-algebra.test.ts
@@ -34,7 +34,9 @@ describe("expanded exact Laplace mathematics", () => {
expect(verifyLaplaceTime("1", [])).toMatchObject({
status: "incorrect",
});
- expect(verifyLaplaceTime("\\delta(t)", []).status).toBe("incorrect");
+ expect(verifyLaplaceTime(String.raw`\delta(t)`, []).status).toBe(
+ "incorrect",
+ );
});
it("preserves exact fractional support boundaries and ROC labels", () => {
const input = spec({ poles: [f("-1/3")], delay: "1/3" });
@@ -43,7 +45,7 @@ describe("expanded exact Laplace mathematics", () => {
"correct",
);
expect(formatRoc(rocBounds(input.poles, -1), input.poles)).toBe(
- "\\operatorname{Re}(s)>-\\frac{1}{3}",
+ String.raw`\operatorname{Re}(s)>-\frac{1}{3}`,
);
expect(() => rocBounds([f("1"), f("1.00000000000000001")], 1)).toThrow(
"too close",
@@ -65,14 +67,17 @@ describe("expanded exact Laplace mathematics", () => {
it("inverts repeated, conjugate, delayed, and constant-quotient terms", () => {
for (const [input, expected] of [
[spec({ gain: "6", poles: [f("-4", 4)] }), "t^3e^{-4t}u(t)"],
- [spec({ poles: [f("-3", 1, "5")] }), "e^{-3t}\\sin(5t)u(t)/5"],
+ [
+ spec({ poles: [f("-3", 1, "5")] }),
+ String.raw`e^{-3t}\sin(5t)u(t)/5`,
+ ],
[
spec({ gain: "4", poles: [f("-5")], delay: "2" }),
"4e^{-5(t-2)}u(t-2)",
],
[
spec({ zeros: [f("-6")], poles: [f("-2")] }),
- "\\delta(t)+4e^{-2t}u(t)",
+ String.raw`\delta(t)+4e^{-2t}u(t)`,
],
] as [RationalSpec, string][]) {
const data = decompose(input),
@@ -106,8 +111,8 @@ describe("expanded exact Laplace mathematics", () => {
for (const answer of [
"e^{-(t-2)}u(t)",
"e^{-(t-2)}u(t-2)+u(t-100)",
- "e^{-(t-2)}u(t-2)+\\delta(t-100)",
- "e^{-(t-2)}u(t-2)+\\delta'(t)",
+ String.raw`e^{-(t-2)}u(t-2)+\delta(t-100)`,
+ String.raw`e^{-(t-2)}u(t-2)+\delta'(t)`,
])
expect(verifyLaplaceTime(answer, terms).status).not.toBe("correct");
expect(verifyLaplaceS("1/(s+1)+1/(s+100)", "1/(s+1)").status).toBe(
diff --git a/tests/unit/laplace-answer-entry.test.ts b/tests/unit/laplace-answer-entry.test.ts
index e20543f9..6d8aee83 100644
--- a/tests/unit/laplace-answer-entry.test.ts
+++ b/tests/unit/laplace-answer-entry.test.ts
@@ -68,7 +68,7 @@ describe("guided Laplace answer entry", () => {
expect(fieldTasks).toHaveLength(2);
for (const task of fieldTasks) {
expect(renderLaplaceFields(task.frame, {})).toContain(
- "\\square",
+ String.raw`\square`,
);
expect(
validateLaplaceTask(task, "", {}, problem.terms).result
@@ -125,7 +125,7 @@ describe("guided Laplace answer entry", () => {
verifyLaplaceTime(prefix + problem.response, problem.terms)
.status,
).toBe("correct");
- const lhs = "y_{\\mathrm{ZI}}(t)";
+ const lhs = String.raw`y_{\mathrm{ZI}}(t)`;
expect(
verifyLaplaceTime(`${lhs}=${problem.response}`, problem.terms, lhs)
.status,
diff --git a/tests/unit/laplace-choice-presentation.test.ts b/tests/unit/laplace-choice-presentation.test.ts
index 675349ef..e5e0cf7e 100644
--- a/tests/unit/laplace-choice-presentation.test.ts
+++ b/tests/unit/laplace-choice-presentation.test.ts
@@ -14,7 +14,7 @@ describe("Laplace choice presentation", () => {
expect(choices[kind]!.math).toContain(
side === "left" ? "u(d-t)" : "u(t-d)",
);
- expect(choices.impulse!.math).toBe("A\\delta(t-d)");
+ expect(choices.impulse!.math).toBe(String.raw`A\delta(t-d)`);
}
});
/** Method descriptions explain the operation without disclosing applicability. */
diff --git a/tests/unit/laplace-constant-preview.test.ts b/tests/unit/laplace-constant-preview.test.ts
index e21d268c..ee8e53aa 100644
--- a/tests/unit/laplace-constant-preview.test.ts
+++ b/tests/unit/laplace-constant-preview.test.ts
@@ -50,7 +50,7 @@ describe("Laplace constant preview eligibility", () => {
gain: value,
}),
value,
- ).not.toContain("\\square");
+ ).not.toContain(String.raw`\square`);
}
});
/** Invalid, nonfinite, unsupported and canceled-variable drafts never become completed mathematical previews. */
@@ -76,7 +76,7 @@ describe("Laplace constant preview eligibility", () => {
gain: value,
}),
value,
- ).toContain("\\square");
+ ).toContain(String.raw`\square`);
}
});
/** Preview validity never validates a wrong quotient or weakens exact comparisons. */
diff --git a/tests/unit/laplace-construction.test.ts b/tests/unit/laplace-construction.test.ts
index ca8c919f..b9d68826 100644
--- a/tests/unit/laplace-construction.test.ts
+++ b/tests/unit/laplace-construction.test.ts
@@ -75,7 +75,7 @@ describe("exact learner-built Laplace mathematics", () => {
);
expect(
tasks.find((task) => task.id === "division")!.hints[2],
- ).toContain("\\deg D=3");
+ ).toContain(String.raw`\deg D=3`);
expect(tasks.find((task) => task.id === "method")!.hints[2]).toContain(
"s^{3}+21s^{2}+147s+343",
);
diff --git a/tests/unit/laplace-elimination.test.ts b/tests/unit/laplace-elimination.test.ts
index 6bc8fe6d..6fd588c3 100644
--- a/tests/unit/laplace-elimination.test.ts
+++ b/tests/unit/laplace-elimination.test.ts
@@ -47,17 +47,20 @@ describe("checked coefficient elimination", () => {
["A", "B"],
);
expect(tasks).toHaveLength(4);
+ expect(tasks[0]!.hints[2]).toContain(String.raw`\frac{1}{2}`);
expect(tasks[0]!.fields.map((field) => field.target)).toEqual([
"1",
- "\\frac{1}{2}",
- "\\frac{1}{2}",
+ String.raw`\frac{1}{2}`,
+ String.raw`\frac{1}{2}`,
]);
- expect(tasks.at(-1)!.fields.at(-1)!.target).toBe("\\frac{1}{3}");
+ expect(tasks.at(-1)!.fields.at(-1)!.target).toBe(
+ String.raw`\frac{1}{3}`,
+ );
const later = tasks.filter((task) => task.operation!.column > 0);
expect(later.length).toBeGreaterThan(0);
for (const task of later) {
expect(task.hints[2]).toContain("This entry changes");
- expect(task.hints[2]).not.toContain("\\frac{0}");
+ expect(task.hints[2]).not.toContain(String.raw`\frac{0}`);
}
for (const task of tasks) {
expect(task.operation!.after).toEqual(
diff --git a/tests/unit/laplace-fixtures.ts b/tests/unit/laplace-fixtures.ts
index 52bd91c4..a5e573a2 100644
--- a/tests/unit/laplace-fixtures.ts
+++ b/tests/unit/laplace-fixtures.ts
@@ -8,11 +8,17 @@ export const inverseFixtures = [
/** Standard-pair fixtures include repeated, complex, delayed, and impulse terms. */
export const pairFixtures = [
- { transform: "(3s+8)/(s^2+16)", inverse: "(3\\cos(4t)+2\\sin(4t))u(t)" },
- { transform: "(s+3)/((s+3)^2+25)", inverse: "e^{-3t}\\cos(5t)u(t)" },
+ {
+ transform: "(3s+8)/(s^2+16)",
+ inverse: String.raw`(3\cos(4t)+2\sin(4t))u(t)`,
+ },
+ {
+ transform: "(s+3)/((s+3)^2+25)",
+ inverse: String.raw`e^{-3t}\cos(5t)u(t)`,
+ },
{ transform: "4e^{-2s}/(s+5)", inverse: "4e^{-5(t-2)}u(t-2)" },
{ transform: "6/(s+4)^4", inverse: "t^3e^{-4t}u(t)" },
- { transform: "5+6/(s+2)", inverse: "5\\delta(t)+6e^{-2t}u(t)" },
+ { transform: "5+6/(s+2)", inverse: String.raw`5\delta(t)+6e^{-2t}u(t)` },
] as const;
/** Forward fixtures avoid the undefined product of an impulse with a discontinuous step. */
@@ -20,5 +26,5 @@ export const forwardFixtures = [
{ transform: "(6s+26)/((s+3)(s+5))", inverse: "(4e^{-3t}+2e^{-5t})u(t)" },
{ transform: "3/((s+1)(s+4))", inverse: "(e^{-t}-e^{-4t})u(t)" },
{ transform: "(5s+6)/(s(s+2))", inverse: "(3+2e^{-2t})u(t)" },
- { transform: "(s+6)/(s+2)", inverse: "\\delta(t)+4e^{-2t}u(t)" },
+ { transform: "(s+6)/(s+2)", inverse: String.raw`\delta(t)+4e^{-2t}u(t)` },
] as const;
diff --git a/tests/unit/laplace-formatting.test.ts b/tests/unit/laplace-formatting.test.ts
index 82c5dce9..b7f2129f 100644
--- a/tests/unit/laplace-formatting.test.ts
+++ b/tests/unit/laplace-formatting.test.ts
@@ -39,7 +39,7 @@ describe("precedence-aware Laplace notation", () => {
expect(signalLatex(term({ amplitude: "0" }))).toBe("0");
expect(
signalLatex(term({ kind: "impulse", amplitude: "-1", delay: "1" })),
- ).toBe("-\\delta(t-1)");
+ ).toBe(String.raw`-\delta(t-1)`);
expect(signalLatex(term({ rate: "-1", delay: "1" }))).toBe(
"e^{-(t-1)}u(t-1)",
);
@@ -48,7 +48,7 @@ describe("precedence-aware Laplace notation", () => {
responseLatex([term(), term({ amplitude: "-1", delay: "1" })]),
).toBe("u(t)-u(t-1)");
expect(signalTransform(term({ amplitude: "-1", delay: "1" }))).toBe(
- "-e^{-s}\\frac{1}{s}",
+ String.raw`-e^{-s}\frac{1}{s}`,
);
expect(
factorProductLatex([
@@ -63,7 +63,7 @@ describe("precedence-aware Laplace notation", () => {
).toBe("2(s+1)^{2}");
expect(
rationalLatex({ n: [fraction(-1)], d: [fraction(0), fraction(1)] }),
- ).toBe("-\\frac{1}{s}");
+ ).toBe(String.raw`-\frac{1}{s}`);
expect(scaledLatex(fraction(-1), "t-1", true)).toBe("-(t-1)");
});
/** Independently authored time and transform answers catch sign/grouping regressions in both support directions. */
diff --git a/tests/unit/laplace-input-entry.test.ts b/tests/unit/laplace-input-entry.test.ts
index 112f4b35..8ce55c63 100644
--- a/tests/unit/laplace-input-entry.test.ts
+++ b/tests/unit/laplace-input-entry.test.ts
@@ -34,7 +34,14 @@ describe("declared Laplace input domains", () => {
it("accepts exact literals while keeping incomplete numbers invalid", () => {
for (const value of ["-3/2", "0.125", "-2", "1/.5"])
expect(entryIssue(value, { kind: "literal" }), value).toBeNull();
- for (const value of ["-", ".", "1/", "1/0", "1+2", "\\frac{1}{2}"])
+ for (const value of [
+ "-",
+ ".",
+ "1/",
+ "1/0",
+ "1+2",
+ String.raw`\frac{1}{2}`,
+ ])
expect(entryIssue(value, { kind: "literal" })?.status, value).toBe(
"invalid",
);
diff --git a/tests/unit/laplace-ode-tutor.test.ts b/tests/unit/laplace-ode-tutor.test.ts
index 60fbc71f..aa07e627 100644
--- a/tests/unit/laplace-ode-tutor.test.ts
+++ b/tests/unit/laplace-ode-tutor.test.ts
@@ -42,7 +42,7 @@ describe("Laplace initial-value guidance", () => {
.flatMap((stage) => stage.tasks)
.filter((task) => task.id.startsWith("jump-"));
expect(jumps).toHaveLength(1);
- expect(jumps[0]!.answer).toBe("\\frac{5}{2}");
+ expect(jumps[0]!.answer).toBe(String.raw`\frac{5}{2}`);
expect(
problem.stages
.flatMap((stage) => stage.tasks)
diff --git a/tests/unit/laplace-support.test.ts b/tests/unit/laplace-support.test.ts
index 02180cb4..b0db1204 100644
--- a/tests/unit/laplace-support.test.ts
+++ b/tests/unit/laplace-support.test.ts
@@ -98,7 +98,7 @@ describe("checked support interval evidence", () => {
validateLaplaceTask(task, "", values, []).result.status,
).toBe("invalid");
}
- expect(tasks.at(-1)!.formula).toContain("\\begin{cases}");
+ expect(tasks.at(-1)!.formula).toContain(String.raw`\begin{cases}`);
});
/** Equivalent rational delays create one boundary and impulses stay separate. */
it("deduplicates exact boundaries and retains separate impulse metadata", () => {
@@ -109,8 +109,8 @@ describe("checked support interval evidence", () => {
];
const tasks = supportTasks(original, original);
expect(tasks.filter((task) => task.kind === "fields")).toHaveLength(2);
- expect(tasks[0]!.formula).toContain("\\delta");
- expect(tasks.at(-1)!.hints[1]).toContain("\\delta");
+ expect(tasks[0]!.formula).toContain(String.raw`\delta`);
+ expect(tasks.at(-1)!.hints[1]).toContain(String.raw`\delta`);
});
/** Tests symbolic identities over the complete interval, not one numerical sample. */
it("accepts equivalent ordinary expressions and rejects support functions, impulses, and wrong sums", () => {
@@ -121,7 +121,7 @@ describe("checked support interval evidence", () => {
expect(verifyLaplaceInterval("2t", "2t-1", interval).status).toBe(
"incorrect",
);
- for (const expression of ["u(t)", "\\delta(t-1)"])
+ for (const expression of ["u(t)", String.raw`\delta(t-1)`])
expect(
verifyLaplaceInterval(expression, "1", interval).status,
).toBe("invalid");
diff --git a/tests/unit/laplace.test.ts b/tests/unit/laplace.test.ts
index bd302ea9..53b60283 100644
--- a/tests/unit/laplace.test.ts
+++ b/tests/unit/laplace.test.ts
@@ -1,4 +1,5 @@
-import { describe, expect, it } from "vitest";
+import katex from "katex";
+import { describe, expect, it, vi } from "vitest";
import {
determineStability,
evaluatePfdResidues,
@@ -31,7 +32,9 @@ describe("Laplace Transform Math Engine (laplace.ts)", () => {
it("should identify causal system as BIBO stable if all poles are in LHP", () => {
const stability = determineStability([-2, -3], "right-sided");
expect(stability.isBiboStable).toBe(true);
- expect(stability.rocLatex).toBe("\\operatorname{Re}(s) > -2");
+ expect(stability.rocLatex).toBe(
+ String.raw`\operatorname{Re}(s) > -2`,
+ );
});
it("should identify causal system as unstable if any pole is in RHP", () => {
@@ -56,6 +59,24 @@ describe("Laplace Transform Math Engine (laplace.ts)", () => {
expect(problem.solutionSteps.length).toBeGreaterThanOrEqual(2);
});
+ /** Confirms the trigonometric inverse pairs render with complete fraction groups. */
+ it("renders the direct inverse trigonometric transform pairs", () => {
+ const random = vi.spyOn(Math, "random").mockReturnValue(0);
+
+ try {
+ const problem = generateLaplaceProblem("inverse_direct");
+ const latex = problem.solutionSteps[1]!.latex;
+
+ expect(latex).toContain(String.raw`\frac{s}{s^2 + 2^2}`);
+ expect(latex).toContain(String.raw`\frac{2}{s^2 + 2^2}`);
+ expect(() =>
+ katex.renderToString(latex, { throwOnError: true }),
+ ).not.toThrow();
+ } finally {
+ random.mockRestore();
+ }
+ });
+
it("should generate valid forward Laplace transform practice problem", () => {
const problem = generateLaplaceProblem("forward");
expect(problem.id).toBeDefined();
diff --git a/tests/unit/lint-escaped-latex.test.ts b/tests/unit/lint-escaped-latex.test.ts
new file mode 100644
index 00000000..f80b4787
--- /dev/null
+++ b/tests/unit/lint-escaped-latex.test.ts
@@ -0,0 +1,190 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { expect, it } from "vitest";
+import {
+ findEscapedLatexViolations,
+ lintPaths,
+} from "../../scripts/lint-escaped-latex.mjs";
+
+const backslash = String.fromCharCode(92);
+const escapedBackslash = backslash + backslash;
+const tick = String.fromCharCode(96);
+
+/**
+ * Detects escaped LaTeX commands in quoted strings and interpolated templates.
+ */
+it("detects escaped commands in quoted strings and untagged templates", function detectsEscapedStrings() {
+ const templateSource = [
+ "const interpolated = ",
+ tick,
+ escapedBackslash + "text{",
+ "${label}",
+ "}",
+ tick,
+ ";",
+ ].join("");
+ const source = [
+ 'const quoted = "' + escapedBackslash + "frac{x}{y}" + '";',
+ templateSource,
+ "",
+ ].join("\n");
+ const violations = findEscapedLatexViolations(source, "fixture.ts");
+
+ expect(violations).toHaveLength(2);
+ expect(violations[0]?.line).toBe(1);
+ expect(violations[0]?.command).toBe(backslash + "frac");
+ expect(violations[1]?.line).toBe(2);
+ expect(violations[1]?.command).toBe(backslash + "text");
+});
+
+/**
+ * Detects escaped Greek LaTeX commands used in project math expressions.
+ */
+it("detects escaped Greek LaTeX commands", function detectsEscapedGreekCommands() {
+ const source =
+ 'const formula = "' +
+ escapedBackslash +
+ "beta " +
+ escapedBackslash +
+ "gamma " +
+ escapedBackslash +
+ 'lambda";';
+ const violations = findEscapedLatexViolations(source, "fixture.ts");
+
+ expect(violations).toEqual([
+ { line: 1, command: backslash + "beta", offset: expect.any(Number) },
+ { line: 1, command: backslash + "gamma", offset: expect.any(Number) },
+ { line: 1, command: backslash + "lambda", offset: expect.any(Number) },
+ ]);
+});
+
+/**
+ * Detects escaped LaTeX in Svelte script and markup expressions.
+ */
+it("detects escaped commands in Svelte expressions", function detectsSvelteExpressions() {
+ const source = [
+ '',
+ '