-1

My function works as I expect (I think) but I want to change my loops with higher order functions, but I'm struggling a bit..

Here is my code :

const getKeywords = (str) => {
    var i, j, result = [];
    for (i = 0; i < str.length; i++) {
        for (j = i + 1; j < str.length + 1; j++) {
            result.push(str.slice(i, j).toLowerCase());
        }
    }
    return result;
}

console.log(getKeywords("testing my function"))

If someone has an idea of which Higher Order Functions to use to replace my nested loop thank you :)

Yoël Zerbib
  • 125
  • 7

1 Answers1

1

Try like this:

const getKeywords = (str) => {
  return [].concat.apply([], str.split("").map((currentValue, i, a) => {
    return a.filter((currentValue, j) => i <= j).map((currentValue, k, b) => { 
      return b.filter((currentValue, l) => l <= k ).join("").toLowerCase();
    });
  }))
}

console.log(getKeywords("testing my function"));

Process:

  1. Use the split() function to convert the string to an array of characters (["t","e","s","t", etc ])
  2. Loop through each character in that array (index i). As you are going through the entire array and returning an element each time, use map().
  3. For each map index i, loop through and return an array of elements where index j is greater than or equal to i (duplicate the array, removing the first character each time). This is conditional and returns an array, so you use filter().
  4. For each of those (map(), index k), return an array of elements up to that index (filter, index l, condition l <= k)
  5. Join the results of that last filter to a string using join() and make that lowercase.
  6. use concat() and apply() to flatten the results to a single array.
sbgib
  • 4,666
  • 3
  • 12
  • 21