Skip to content
Snippets Groups Projects

random_keyword_response_function.js

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Evan Raskob
    Edited
    responseGenerator.js 1.62 KiB
    // this is the array of keywords and responses to them 
    var responsesArray = [
        {
            keyword: "good",
            response: "That's great!"
        },
        {
            keyword: "bad",
            response: "I'm so sorry!"
        }
        // ADD MORE KEYWORDS HERE
    ];
    
    /**
     * Choose an approriate textual response based on a keyword and list of keyword/response mappings
     * 
     * @param {String} textToSearch 
     * @param {Array} keywordsList 
     * @returns {String} A response based on the keywords, or "" (null) otherwise
     * @example Try running this in the browser console: chooseResponseByKeyword("I feel good!", responsesArray);
     */
    function chooseResponseByKeyword(textToSearch, keywordsList) {
    
        // before we get complicated, let's try something simple
        // use String.prototype.indexOf( search string ) to find the string in the input text.
        // indexOf() returns a positive number (the index in the string) if found, or -1 if not found.
    
        // this is a testing keyword, not for the final version
        //let testKeyword = "good"; // a test keyword to search for in the input text
        //let foundIndex = textToSearch.indexOf(testKeyword); // did we find it?
    
        let response = ""; // the response from the bot
    
        for ( let i=0; i < responsesArray.length; i++ )
        {
            let current = responsesArray[i];
            let foundIndex = textToSearch.indexOf(current.keyword);
            if (foundIndex > -1)
            {
                response = current.response; // set the final response = the bot's response
            }
        }
    
        if (response !== "") {
            console.log("found [" + testKeyword + "] in string [" + textToSearch + "]");
        }
    
        return response;
    }
    0% or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment