javascriptarraysstringfunctioncurrying

Why is my function returning undefined when using another function as a parameter?


The problem I am having is with the following code:

/**
 * @param {(sentence: string) => boolean} criterion - a function that
 *  takes a sentence and returns a boolean
 * @param {string[]} sentences - an array of space-separated strings of words
 * @returns {string[]} the subset of `sentences` for which `criterion` returns true
 */
const getRelevantSentences = (about, sentences) => {
    const arr = [];
      if(about(sentences) == true){
        arr.push(sentences);
        return arr;
      }
}

This above function is supposed to take another function and an array as arguments, and then pass out an array of strings that make the function return true. In this instance, I am trying to test whether or not the specific "sentence" string within the "sentences" array makes the about() function return true. In other words, I am returning any strings that are "similar" to that of another string.

Below is the code that makes up the about() function:

/**
 * @param {string[]} topics - an array of topic words
 * @param {string} sentence - a space-separated string of words
 * @returns {boolean} whether `sentence` contains any of the words in `topics`
 */
const isRelevant = (topics, sentence) => {
  for(i=0; i<topics.length;i++){
    if (sentence.includes(topics[i])) {
      return true;
    }
    else {
      return false;
    }
  }
};

/**
 * @param {string[]} topics - an array of topic words
 * @returns {(sentence: string) => boolean} a function that takes a sentence
 *  and returns whether it is relevant to `topics`
 */
const about = (topics) => {
    return function(sentence) {
      return isRelevant(topics,sentence);
    }
};

The data used as input is:

const sentence = "the quick brown fox jumps over the lazy dog"

const sentences = "I have a pet dog", "I have a pet cat", "I don't have any pets"

How can I resolve this issue?


Solution

  • As it stands, the function returns nothing (undefined) whenever about(sentences) is false. Please rewrite the function as follows:

    const getRelevantSentences = (about, sentences) => {
        const arr = [];
        if(about(sentences)){
            arr.push(sentences);
        }
        return arr;
    }
    

    Or, as follows:

    const getRelevantSentences = (about, sentences) => {
        if(about(sentences)){
            return [sentences];
        } else {
            return [];
        }
    }