generated from freeCodeCamp/template
-
-
Notifications
You must be signed in to change notification settings - Fork 25
Open
Labels
bugSomething isn't workingSomething isn't working
Description
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:
| const body = "[^}]*"; |
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
functionRegexto only match the head of the function? (i.e. hardcodeincludeBodytofalse) - 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
acornparses the function, that I used in the example above.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working