Last active
August 5, 2021 13:54
-
-
Save kingisaac95/b97a0db96c23da962a62e511738b70af to your computer and use it in GitHub Desktop.
A simple algorithm to search through a contact list; where contact list is an array with first and last names spaced out.
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 sampleData = ['tom harry', 'dike harry', 'girl guy', 'boo baa']; | |
/** | |
* use first/last name to create regex pattern | |
* if no last name return first name pattern | |
*/ | |
const getSearchPattern = (terms, index) => | |
new RegExp(".*" + (terms[index] ? terms[index] : terms[0]) + ".*"); | |
const searchUsers = (searchTerm) => { | |
const searchTerms = searchTerm.split(' '); | |
const fNamePattern = getSearchPattern(searchTerms, 0); | |
const lNamePattern = getSearchPattern(searchTerms, 1); | |
const results = sampleData.filter((each) => | |
fNamePattern.test(each) || lNamePattern.test(each)); | |
console.log(results); | |
} | |
// test | |
searchUsers('dik tom'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment