PERF: Avoid excessive object creations in watched words (#27354)

Inline the helper functions, avoid creating and then immediately destructuring arrays, use complete strings instead of string interpolation, Map instead of a pojo.
This commit is contained in:
Jarek Radosz
2024-06-10 14:44:31 +02:00
committed by GitHub
parent 71391cd40d
commit 42a529f9ae
6 changed files with 51 additions and 67 deletions

View File

@@ -196,7 +196,7 @@ function applyEmoji(
enableShortcuts,
inlineEmoji,
customEmojiTranslation,
watchedWordsReplacer,
watchedWordsReplace,
emojiDenyList
) {
let result = null;
@@ -206,19 +206,16 @@ function applyEmoji(
content = emojiUnicodeReplacer(content);
}
if (watchedWordsReplacer) {
const watchedWordRegex = Object.keys(watchedWordsReplacer);
watchedWordRegex.forEach((watchedWord) => {
if (content?.match(watchedWord)) {
const regex = new RegExp(watchedWord, "g");
if (content && watchedWordsReplace) {
Object.entries(watchedWordsReplace).forEach(([regexpString, options]) => {
if (content.match(regexpString)) {
const regex = new RegExp(regexpString, "g");
const matches = content.match(regex);
const replacement = watchedWordsReplacer[watchedWord].replacement;
matches.forEach(() => {
const matchingRegex = regex.exec(content);
if (matchingRegex) {
content = content.replace(matchingRegex[1], replacement);
content = content.replace(matchingRegex[1], options.replacement);
}
});
}
@@ -226,9 +223,9 @@ function applyEmoji(
}
// prevent denied emoji and aliases from being rendered
if (emojiDenyList?.length > 0) {
if (content && emojiDenyList?.length > 0) {
emojiDenyList.forEach((emoji) => {
if (content?.match(emoji)) {
if (content.match(emoji)) {
const regex = new RegExp(`:${emoji}:`, "g");
content = content.replace(regex, "");
}

View File

@@ -1,8 +1,3 @@
import {
createWatchedWordRegExp,
toWatchedWord,
} from "discourse-common/utils/watched-words";
const MAX_MATCHES = 100;
function isLinkOpen(str) {
@@ -59,11 +54,12 @@ export function setup(helper) {
if (md.options.discourse.watchedWordsReplace) {
Object.entries(md.options.discourse.watchedWordsReplace).forEach(
([regexpString, options]) => {
const word = toWatchedWord({ [regexpString]: options });
matchers.push({
word: new RegExp(options.regexp, options.case_sensitive ? "" : "i"),
pattern: createWatchedWordRegExp(word),
pattern: new RegExp(
regexpString,
options.case_sensitive ? "gu" : "gui"
),
replacement: options.replacement,
link: false,
html: options.html,
@@ -75,11 +71,12 @@ export function setup(helper) {
if (md.options.discourse.watchedWordsLink) {
Object.entries(md.options.discourse.watchedWordsLink).forEach(
([regexpString, options]) => {
const word = toWatchedWord({ [regexpString]: options });
matchers.push({
word: new RegExp(options.regexp, options.case_sensitive ? "" : "i"),
pattern: createWatchedWordRegExp(word),
pattern: new RegExp(
regexpString,
options.case_sensitive ? "gu" : "gui"
),
replacement: options.replacement,
link: true,
});