Table of contents
No headings in the article.
Hi!
This task I found a bit funny that is why I decided to try it. We will be given a string and we will create a function to check how many potato words are in this string. So for example.
'potatopotatoapple' - here our function should return 2 'potatopotatoappleorangepotatoplumwatermelonpotatopot' - here our function should return 4
Code
Our main logic will be two loops. It is very important that this loops have correct iteration variables.
So our first loop will iterate through all letters inside given string. It is important that we do not go beyond the string. That is why we apply condition j<word.length-5. Why 5 and not 6 if our potato has 6 letters? That is because we are counting from 0.
Second loop we will use to save six letters couning from j loop position.
for(let j=0; j<word.length-5; j++){
for(let i=j; i< j+6; i++) {
}
}
Next we add our conditions to check if we have potato. We create two variables to count our potatoes and second to save our 6 letters.
So we start our loops, after first iteration of first loop we save 6 first letters to potato variable. Then we check if our saved letters are equal to word 'potato'. If yes we add one potato to our countpotato variable. Last we erase our 6 saved letters and hop to second iteration of the first loop.
function checkPotato(word){
let countpotato = 0;
let potato = '';
for(let j=0; j<word.length-5; j++){
for(let i=j; i< j+6; i++) potato += word[i];
if (potato == "potato") countpotato++;
potato = '';
}
return countpotato;
}
And this is it, if we call our function we will get a reply how many potato words are in our string.
console.log("You have " + checkPotato(givenword) + " potatoes!");
Of course I thought that there must be a simplier way to check this. And I did small reasearch and found match() function.
So with this function we could call it as word.match(/potato/g) and it will return an array of matches. So for our string 'potatopotatoapple' we will receive array with [ 'potato', 'potato' ].
So we only need to check this array length and we will have our result. Almost! Because if there is no potato in our string function word.match(/potato/g) will return null. That is why if its null we take empty array instead which length will be 0.
So our final function would look like this.
function checkPotato(word){
var countpotato = (word.match(/potato/g) || []).length;
return countpotato;
}
If you find any mistakes or you have ideas how to refactor my solutions to be simplier/ better please let me know :)