gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
refactor code: class Highliter { constructor(wheresearch, anypatterns) {…
- User
refactor code: class Highliter { constructor(where_search, any_patterns) { this.where_search = where_search; this.any_patterns = any_patterns; // expected as an object { regex: className } }
search_for_replace() { // mimic json encode/decode safely by cloning string (redundant in JS but keeping structure) let where_search = JSON.parse(JSON.stringify(this.where_search));
code// replace new lines with spaces where_search = where_search.replace(/\n/g, ' '); console.log(JSON.stringify(["any_patterns", this.any_patterns])); console.log(JSON.stringify(["where_search", where_search])); const ready_all_patterns = []; const ready_for_replace_style = []; for (const [patternStr, className] of Object.entries(this.any_patterns)) { // Create RegExp object from string pattern //(assume patternStr includes delimiters and //flags like "/pattern/gi") // Remove slashes and parse flags manually: const match = patternStr.match(/^\/(.+)\/([gimsuy]*)$/); if (!match) continue; // skip invalid patterns const [_, patternBody, flags] = match; const regex = new RegExp(patternBody, flags); // Find all matches let matchArray; while ((matchArray = regex.exec(where_search)) !== null) { const for_replace = matchArray[0]; const what_search_for_replace = for_replace; const replace_style = `<span class='${className}'>${for_replace}</span>`; if (!ready_all_patterns.includes(what_search_for_replace)) { ready_all_patterns.push(what_search_for_replace); ready_for_replace_style.push(replace_style); } // Avoid infinite loop if zero width match: if (regex.lastIndex === match.index) { regex.lastIndex++; } } } const res = { ready_all_patterns, ready_for_replace_style, where_search, }; // console.log("search_for_replace(), ", JSON.stringify(res)); return res; - Assistant
Here's a refactored version of your
Highliterclass, improving readability, variable naming, and removing some redundant cloning. Comments remain for clarity, and modern JS features are used where appropriate:js