nblackburn
8/3/2018 - 1:27 PM

Consecutive search

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;
};