One test doesnt check for some reason

Hey guys!
This loop i just wrote has checked every test except the following:
confirmEnding("Open sesame", "same") should return true.
for some the if statement isnt executing. Why? The following tests are almost exactly the same but false (targets “game” and “sage”) and they checked, so i asume they do return the boolean after executing.
Another thing i’d like to ask is about the code itself. I checked the solution to see if the problem was something simple that i was missing and it made me realize that my code is kinda wacky compared to the very simple example. Should i be worried about it?


function confirmEnding(str, target) {
let  i = 0;
while (i <= str.length - target.length) {
  if (i === str.length - target.length) {
    let ya = str.split(str[i-1]);
    let hopeThisWorks = ya.pop();
    console.log(hopeThisWorks);
    return hopeThisWorks == target;
  }
  i++;
}

}
confirmEnding("Open sesame", "same");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36.

Challenge: Confirm the Ending

Link to the challenge:

I’m not sure I understand the logic of your approach.

You use a loop to figure out the different between str.length and target.length. Can’t we just calculate that?

let ya = str.split(str[i - 1]);

Why do we want to split it along the char at that char? In this case it is the letter “e”. There are are 3 of those in there. I see that you are trying to break off the end of str that is the same length as target - that is a good approach. I just think you can find an easier way to do it. Do you know how to break strings into substrings?

let hopeThisWorks = ya.pop();

Of course, because of how you’ve split your strings, this is giving you and empty string.

I think you need to rethink your algorithm. If you were to explain how to do this to someone, check if the end of a word matches the target string, how would you tell them to do it. Don’t think about computer languages, just the algorithm. Whatever you come up with, JS probably has a way to do it.

I can think of two simple ways to do this. The first one is the one that you appear to be trying but it doesn’t need a loop. The other way uses a loop, but in a different way.

1 Like

I dont know why i thought that using split() with bracket notation there would separate by the index and not the character in there. Thanks so much for answering!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.