Created
August 3, 2018 13:27
-
-
Save nblackburn/5c1f1dcf0397e78a2ee7573aea3a543a to your computer and use it in GitHub Desktop.
Consecutive search
This file contains 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
module.exports = (query, result, insensitive) => { | |
let index = 0; | |
let last = 0; | |
let matched = false; | |
// Normalize the strings we are comparing to each other. | |
if (insensitive) { | |
query = query.toLowerCase(); | |
result = result.toLowerCase(); | |
} | |
while (index < query.length) { | |
let character = query.charAt(index); | |
let fromIndex = (index > 0) ? (last + 1) : last; | |
let resultCharIndex = result.indexOf(character, fromIndex); | |
// If we couldn't find the character from the last matched index, then we don't have a match. | |
if (resultCharIndex === -1) { | |
matched = false; | |
break; | |
} | |
index++; | |
last = resultCharIndex; | |
if (index === query.length) { | |
matched = true; | |
break; | |
} | |
} | |
return matched; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment