Better code for Confirm The Ending challenge?

Better code for Confirm The Ending challenge?
0

#1

Hi, I just completed the Confirm the Ending challenge:


and it checks out ok, but I wanted to know if anyone could tell me if the code below could be written better.

function confirmEnding(str, target) {
  
  var firstString = str.split(" ");
  var result = "";
  var popped = firstString.pop();
 
  var oneWordCount = target.length;
  var lastString = target.substring(oneWordCount);
  var chkString = str.substring(str.length - oneWordCount);
  
  if ((popped === target) || (lastString === target) || (chkString === target)){
     return true;
  } else {
    return false;
  }
  
}

confirmEnding("Bastian", "an");

Thanks.


#3

Thanks p1xt! That is amazing how so little code can accomplish the same thing.


#4

You do have a few things you could clean up.

Firstly, any time you see a

if (logic) { 
return true; 
} else { 
return false; }

You can replace it with: return (logic)

Secondly, look through the your code for any variables you are not actually using - there is one that you declare that is never used for anything, so you can safely delete it.

Finally, look again at your logic in that if block. For those three cases ((popped === target) || (lastString === target) || (chkString === target)). Think about whether any of these are actually just redundant because one of the other ones implicitly includes their logic. You will find that you only need one of them, not all three :slight_smile:

On preview: Damnit, @P1xt beat me to the punch :blush: (with better code)

Spoiler - show code
function confirmEnding(str, target) {
  
  var firstString = str.split(" ");
  var popped = firstString.pop();
 
  var oneWordCount = target.length;
  var lastString = target.substring(oneWordCount);
  var chkString = str.substring(str.length - oneWordCount);
  
  return ((chkString === target));
  
}

confirmEnding("Bastian", "an");

#6

Didn’t know you could simply use a return in a case like that. Thanks!


#7

function confirmEnding(str, target) {
var niz=str.split(’’);
for (i=0;i<(str.length-target.length);i++){
niz.shift();
}
if (niz.join(’’)===target){
return true;
}
else{
return false;
}
}
confirmEnding(“Bastian”, “n”);


#8

This is the very simple solution I came up with-

function confirmEnding(str, target) {

  var subStr = str.substring(str.length-target.length);
  return subStr===target;

}

confirmEnding("Bastian", "n");