Created
November 26, 2024 07:52
-
-
Save DonerKebab/d23c4c91dc21209e3cb0376d4a2342dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const title = "Apple Grade A iPhone 16 Pro Max 256GB White Titan"; | |
const regexes = [ | |
/\bApple(?=\s|$)/i, // Matches "Apple" | |
/\b(Apple\s*)?iPhone(?=\s|$)/i, // Matches "Apple iPhone" | |
/\bApple\s*Air\s*Pods?(?=\s|$)/i, // Matches "Apple Air Pods" | |
/\bApple\s*Watch(?=\s|$)/i // Matches "Apple Watch" | |
]; | |
function getBestMatch(title, regexes) { | |
let bestMatch = { regex: null, match: "", score: 0 }; | |
regexes.forEach((regex) => { | |
const match = title.match(regex); | |
if (match) { | |
// Count how many regex patterns match the title | |
const relatedMatches = regexes.filter(r => r.test(title)).length; | |
// Update best match based on score and match length | |
if ( | |
relatedMatches > bestMatch.score || // Higher score | |
(relatedMatches === bestMatch.score && match[0].length > bestMatch.match.length) // Same score, longer match | |
) { | |
bestMatch = { regex, match: match[0], score: relatedMatches }; | |
} | |
} | |
}); | |
return bestMatch; | |
} | |
const result = getBestMatch(title, regexes); | |
console.log("Best Match:", result.match); | |
console.log("Matched By Regex:", result.regex); | |
console.log("Score (Related Matches):", result.score); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment