Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More efficient regex replace #2411

Merged
merged 1 commit into from
Dec 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 6 additions & 8 deletions src/common/types/chainner-builtin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,25 +189,23 @@ const regexReplaceImpl = (

// rregex currently only supports byte offsets in matches. So we have to
// match spans on UTF8 and then convert it back to Unicode.
const utf8 = Buffer.from(text, 'utf8');
const toUTF16 = (offset: number) => {
return utf8.toString('utf8', 0, offset).length;
};
const utf8 = new TextEncoder().encode(text);
const decoder = new TextDecoder();

let result = '';
let lastIndex = 0;
let lastByteIndex = 0;
for (const match of matches) {
const full = match.get[0];
result += text.slice(lastIndex, toUTF16(full.start));
result += decoder.decode(utf8.slice(lastByteIndex, full.start));

const replacements = new Map<string, string>();
match.get.forEach((m, i) => replacements.set(String(i), m.value));
Object.entries(match.name).forEach(([name, m]) => replacements.set(name, m.value));
result += replacement.replace(replacements);

lastIndex = toUTF16(full.end);
lastByteIndex = full.end;
}
result += text.slice(lastIndex);
result += decoder.decode(utf8.slice(lastByteIndex));

return result;
};
Expand Down