Fast search engine for React with Nextjs

Since this is a small website it's easy to make a searchengine. I created a function that returns a list of searchresults. It's fast and it displays the result in milliseconds. Actually it act more like a filter, because the result is already there, it just needs to be filtered.

Try the searchengine here. See the full code on Bitbucket.

//Prepare list for the search.
    var elements = [];
     
    this.state.data.content.map(c =>
        elements.push({ path: c.path, title: c.title, content: c.content.replace(/<[^>]*>?/gm, '') }));

    this.state.data.projects.posts.filter(c =>
        elements.push({ path: "/projects/" + c.slug, title: c.title, content: c.content.replace(/<[^>]*>?/gm, '') }));

    var searchResults = SearchResult(e, elements, 150);


//Search result class
const SearchResult = (q, list, excerptCount) => {

    var results = [];
    var result = filter(q, list);

    result.map(c =>
        results.push({ path: c.path, title: c.title, content: c.content.substr(0, excerptCount)+'...' }));

    return results;

    function escapeRegExp(s) {
        return s.replace(/[-/\^$*+?.()|[]{}]/g, "\$&");
    }

    function filter(q, list) {
        const words = q
            .split(/s+/g)
            .map(s => s.trim())
            .filter(s => !!s);

        const hasTrailingSpace = q.endsWith(" ");
        const searchRegex = new RegExp(
            words
                .map((word, i) => {
                    if (i + 1 === words.length && !hasTrailingSpace) {
                        // The last word - ok with the word being "startswith"-like
                        return (?=.*\b@{ escapeRegExp(word) });
                    } else {
                        // Not the last word - expect the whole word exactly
                        return (?=.*\b@{ escapeRegExp(word) }\b);
                    }
                })
                .join("") + ".+",
            "gi"
        );
        return list.filter(item => {
            return searchRegex.test(item.content);
        });
    }
};

export default SearchResult;

Created by Bootproject editor on 2019-10-09


  • multi

    About

    The Swede(me), Rickard Magnusson a Senior Software Engineer, currently employeed as a freelance consultant in Norway.

  • Legal

    Bootproject.se and Footer.se is property of Bootproject and may be used under (MIT)licence . See project on Bitbucket

  • Logo Contact

    Email: bootproject@icloud.com

(©) Copyright www.bootproject.no 2020