Describe the bug
The current implementation of functionRegex uses the pattern [^}]* to match function bodies, which means "zero or more characters that are not a closing curly bracket." This causes the regex to stop matching at the first } encountered, rather than at the actual end of the function.
The problematic line:
This definition is only correct for functions whose bodies contain no curly brackets at all.
All three function patterns defined in functionRegex share this limitation:
| Pattern |
Body definition |
| Normal function |
[^}]*\} |
| Arrow function |
[^}]*\}? |
| Anonymous function |
[^}]*\} |
To Reproduce
const regex = __helpers.functionRegex('foo', ['bar'], { capture: true });
const code = "function foo(bar) { console.log(`${bar}`); return bar; }";
const match = code.match(regex);
console.log(match[1]);
The log message reads:
function foo(bar) { console.log(`${bar}
Expected behavior
The log message should read:
function foo(bar) { console.log(`${bar}`); return bar; }
Questions about potential solutions
As far as I know matching balanced/nested curly brackets is not possible with standard regular expressions (at least not with JavaScript's RegExp).
- Should we limit
functionRegex to only match the head of the function? (i.e. hardcode includeBody to false)
- Can we provide a JavaScript parser inside the curriculum tests (creating an abstract syntax tree from the code entered by the learner)? This would allow contributors to write robust tests for any JS challenge that contains nested logic. For example see this ATS Explorer Snippet demonstrating how
acorn parses the function, that I used in the example above.
Describe the bug
The current implementation of
functionRegexuses the pattern[^}]*to match function bodies, which means "zero or more characters that are not a closing curly bracket." This causes the regex to stop matching at the first}encountered, rather than at the actual end of the function.The problematic line:
curriculum-helpers/packages/helpers/lib/index.ts
Line 254 in 111f791
This definition is only correct for functions whose bodies contain no curly brackets at all.
All three function patterns defined in functionRegex share this limitation:
[^}]*\}[^}]*\}?[^}]*\}To Reproduce
The log message reads:
Expected behavior
The log message should read:
Questions about potential solutions
As far as I know matching balanced/nested curly brackets is not possible with standard regular expressions (at least not with JavaScript's RegExp).
functionRegexto only match the head of the function? (i.e. hardcodeincludeBodytofalse)acornparses the function, that I used in the example above.