Skip to content

Instantly share code, notes, and snippets.

@nblackburn
Created August 3, 2018 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblackburn/5c1f1dcf0397e78a2ee7573aea3a543a to your computer and use it in GitHub Desktop.
Save nblackburn/5c1f1dcf0397e78a2ee7573aea3a543a to your computer and use it in GitHub Desktop.
Consecutive search
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