Basic Algorithm Scripting: Confirm the Ending

Basic Algorithm Scripting: Confirm the Ending
0

Hello…

my solution to this…is this okay? it works.

Summary

function confirmEnding(str, target) {
// “Never give up and good luck will find you.”
// – Falcor
var noob = str.length; //get string length
var noob2 = target.length; //get length of target
var result = str.substring(noob-noob2); //here subtract lengths of string and target to extract equivalent end of string
var match = target.substring(); //here outputting target
console.log(match);
console.log(result);
if (match == result){ //matching both sub string outputs
return true;
}
else{
return false;
}

}

confirmEnding(“Bastian”, “n”);

Looks good to me. You could certainly make it shorter in some ways.

For example, this

``````if (match == result) {
return true;
} else {
return false;
}
``````

could just be

``````return match == result;
``````
1 Like

Hi,

It gets the job done, so congrats!

The useless line is `var match = target.substring();` because substring without any arguments will always return the target string, so that line means `var match = target` and you already have a variable with that value: target.

This is your code without that line:

``````function confirmEnding(str, target) {
var noob = str.length;
var noob2 = target.length;
var result = str.substring(noob - noob2);
if (target == result) {
return true;
} else {
return false;
}
}
``````

You can improve it the way @michaelfoland just told you:

``````function confirmEnding(str, target) {
var noob = str.length;
var noob2 = target.length;
var result = str.substring(noob - noob2);
return target == result;
}
``````

Have you seen regular expressions already? I think this example is a good fit for that:

``````function confirmEnding(str, target) {
return new RegExp( target + "\\$" ).test( str );
}
``````

Happy coding!

1 Like

Clear “for” loop

``````
let result = "";
for (let c = 0; c < target.length; c++) {
result += str[c + (str.length - target.length)];
}

return (result === target) ? true : false;
``````

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

I have closed this thread due to the fact it is only people posting solutions.

Thank you for understanding.