Skip to content

Instantly share code, notes, and snippets.

@theuves
Created June 29, 2019 23:07
Show Gist options
  • Save theuves/ce391921e986150239f79d963758631e to your computer and use it in GitHub Desktop.
Save theuves/ce391921e986150239f79d963758631e to your computer and use it in GitHub Desktop.
(WIP) Function to search values of an array.
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