If you missed the introductory post, it's here. For a list of previously solved katas, please refer to the bottom of this page.
If this is your first time seeing my post, please note - these katas are probably randomly assigned per user so please don't go into Codewars thinking we will have exactly the same user experience, I am just posting these in the order that I got them.
Kata #16
DESCRIPTION:
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
solution('abc', 'bc') // returns true
solution('abc', 'd') // returns false
Starting code:
function solution(str, ending){
// TODO: complete
}
My attempt that worked:
const solution = (str, ending) => str.endsWith(ending) ? true : false
Doing a one-liner code is addicting 🤣 *feelsgoodman.jpg*
Rank #1 'Best Practice':
function solution(str, ending){
return str.endsWith(ending);
}
This is probably what I would've typed if I wanted to go the traditional way.
Rank #2 'Best Practice' with the one-liner:
const solution = (str, ending) => str.endsWith(ending);
Huh, so the code could still be shorter. I guess the function without the ternary statement I added was 'truthy' by itself.
Rank #3:
function solution(str, ending){
if (typeof(str) != "string" || typeof(ending) != "string")
throw "wrong type";
if (ending.length>str.length)
return false;
return str.substr(str.length-ending.length, ending.length) == ending;
}
Rank #4 with the .substr() method:
function solution(str, ending){
return str.substr(-ending.length) == ending;
}
Other entries worth mentioning at rank #6 with the use of .slice():
function solution(str, ending){
return str.slice(0 - ending.length) === ending;
}
Rank #8 with .match() submitted by a single person (King.), and the first time I'm seeing it in the wild:
function solution(str, ending){
var l = ending.length;
var str = str.slice(-l);
return str.match(ending) ? true : false;
}
That's it for Kata #16, stay tuned for more katas to be solved!
Link to Kata #1: Square(n) Sum
Link to Kata #2: Convert a Number to a String
Link to Kata #3: DNA to RNA Conversion
Link to Kata #4: Remove First and Last Character
Link to Kata #5: MakeUpperCase
Link to Kata #6: Total amount of points
Link to Kata #7: A Needle in the Haystack
Link to Kata #8: Sum of positive
Link to Kata #9: Basic Mathematical Operations
Link to Kata #10: Beginner - Reduce but Grow
Link to Kata #11: Square Every Digit
Link to Kata #12: Friend or Foe?
Link to Kata #13: Grasshopper - Summation