diff --git a/codeflash/languages/javascript/instrument.py b/codeflash/languages/javascript/instrument.py index ee28c90a6..2ebfee96f 100644 --- a/codeflash/languages/javascript/instrument.py +++ b/codeflash/languages/javascript/instrument.py @@ -179,6 +179,9 @@ def __init__(self, function_to_optimize: FunctionToOptimize, capture_func: str) # Captures: (whitespace)(await )?(object.)*func_name.call( self._dot_call_pattern = re.compile(rf"(\s*)(await\s+)?((?:\w+\.)*){re.escape(self.func_name)}\.call\s*\(") + # Precompile regex to find next special character (quotes or parentheses) + self._special_re = re.compile(r'["\'`()]') + def transform(self, code: str) -> str: """Transform all standalone calls in the code.""" result: list[str] = [] @@ -380,13 +383,18 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N s_len = len(s) quotes = "\"'`" + special_re = self._special_re + while pos < s_len and depth > 0: - char = s[pos] + match = special_re.search(s, pos) + if not match: + return None, -1 + + char = match.group() + char_pos = match.start() - # Handle string literals - # Note: preserve original escaping semantics (only checks immediate preceding char) if char in quotes: - prev_char = s[pos - 1] if pos > 0 else None + prev_char = s[char_pos - 1] if char_pos > 0 else None if prev_char != "\\": if not in_string: in_string = True @@ -400,12 +408,11 @@ def _find_balanced_parens(self, code: str, open_paren_pos: int) -> tuple[str | N elif char == ")": depth -= 1 - pos += 1 + pos = char_pos + 1 if depth != 0: return None, -1 - # slice once return s[open_paren_pos + 1 : pos - 1], pos def _parse_bracket_standalone_call(self, code: str, match: re.Match[str]) -> StandaloneCallMatch | None: