Skip to content

[Bug]: __helpers.functionRegex matches functions containing curly braces in their bodies incompletely #560

@l3onhard

Description

@l3onhard

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).

  1. Should we limit functionRegex to only match the head of the function? (i.e. hardcode includeBody to false)
  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions