Prompt
When implementing algorithms, ensure they are both efficient and correct across all input cases. Key considerations:
-
Pattern matching edge cases: Ensure regex patterns handle all edge cases, including matches at the beginning of strings. For example, replace /[^\\][^\n]+/with/(?:^[^\]) [^\n]+/to catch backticks at string start. -
Algorithmic complexity: Prevent potential denial-of-service vulnerabilities by analyzing time complexity of algorithms, especially regular expressions on user input. For example, avoid patterns like
/^\[([^\]]*)\]\s*(.*)$/that can cause performance issues with certain inputs. - False positive prevention: Configure pattern detection algorithms to avoid false matches. Start pattern searches from length 2 instead of 1 to prevent single repeated elements from being incorrectly identified as patterns:
// Instead of: for (let patternLength = 1; patternLength <= maxPatternLength; patternLength++) { // Use: for (let patternLength = 2; patternLength <= maxPatternLength; patternLength++) { - Precise matching: For keyword detection, use word boundaries instead of simple substring matching to improve accuracy:
// Instead of: return keywords.some((keyword) => text.includes(keyword)) // Use: return keywords.some((keyword) => new RegExp(`\\b${keyword}\\b`).test(text))
Following these practices helps create algorithms that are not only computationally efficient but also robust against edge cases and potential security exploits.