Quality: Unsafe non-null assertion on regex match#1156
Quality: Unsafe non-null assertion on regex match#1156maptoan wants to merge 1 commit intosource-academy:masterfrom
Conversation
The code uses the non-null assertion operator (!) on the result of regex matches (e.g., filename.match(...)![0]). If the filename does not contain the expected pattern, this will throw a TypeError: Cannot read property '0' of null, crashing the generation process. Affected files: tocUtils.ts Signed-off-by: toanmap <174589430+maptoan@users.noreply.github.com>
There was a problem hiding this comment.
Code Review
This pull request refactors the generateChapterIndex function in javascript/tocUtils.ts to replace non-null assertions with explicit null checks for regex matches. However, the refactoring introduced a critical syntax error where an else if statement follows a closed else block, breaking the conditional chain for prefaces and acknowledgements.
| } else { | ||
| const prefacesMatch = filename.match(/prefaces\d*/g); | ||
| if (prefacesMatch) { | ||
| chapterIndex = prefacesMatch[0]; | ||
| } | ||
| } else if (filename.match(/acknowledgements/)) { |
There was a problem hiding this comment.
This refactoring introduces a syntax error. The else if on line 23 is not valid because it follows a complete if-else statement (lines 16-23). An else if must follow an if or another else if without an intervening else block.
To preserve the original logic of a single chain of mutually exclusive checks, the subsequent else if statements should be nested correctly inside the else block.
} else {
const prefacesMatch = filename.match(/prefaces\d*/g);
if (prefacesMatch) {
chapterIndex = prefacesMatch[0];
} else if (filename.match(/acknowledgements/)) {
chapterIndex = "acknowledgements";
}
}
Problem
The code uses the non-null assertion operator (!) on the result of regex matches (e.g., filename.match(...)![0]). If the filename does not contain the expected pattern, this will throw a TypeError: Cannot read property '0' of null, crashing the generation process.
Severity:
highFile:
javascript/tocUtils.tsSolution
Replace the non-null assertion with a safe check: const match = filename.match(/(?<=chapter)\d+/g); if (match) { chapterIndex += '.' + match[0]; }
Changes
javascript/tocUtils.ts(modified)Testing