Created
June 29, 2019 23:07
-
-
Save theuves/ce391921e986150239f79d963758631e to your computer and use it in GitHub Desktop.
(WIP) Function to search values of an array.
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
function createRegex(string) { | |
const regexPrefix = '^'; | |
const regexSuffix = '$'; | |
const regexMain = string.replace(/(.)/g, '($1).*'); | |
const regexContent = `${regexPrefix}${regexMain}${regexSuffix}`; | |
const regex = RegExp(regexContent, 'g'); | |
return regex; | |
} | |
function match(string = '', terms = [], handle = (value) => value) { | |
const regex = createRegex(string); | |
const filterAndHandleMatchedTerms = (term) => { | |
const isMached = regex.test(term); | |
if (isMached) { | |
return term.replace(regex, (_, matchedPart) => { | |
return handle(matchedPart); | |
}); | |
} | |
} | |
return terms | |
.map(filterAndHandleMatchedTerms) | |
.filter(Boolean); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment