Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Confirm the Ending:
function confirmEnding(str, target) {
return str.slice(-target.length)===target;
}
Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Confirm the Ending:
function confirmEnding(str, target) {
return str.slice(-target.length)===target;
}
Aside from using the shorter built-in endsWith
function, it’s probably as short as it can get (or make it tad shorter by using ==
instead of ===
).
I am sorry, but I did not understand You clearly.
Is my solution the shortest or not?
function confirmEnding(str, target) {
return str.slice(-target.length)===target;
}
I’d say it depends on how you look at it. In terms of the number of steps the function does, it’s probably as short as it can get. But in terms of the number of characters used, it can be made shorter, but at the expense of readability of your code.
You are right. It is possible to use using "== " instead of “===”.
Letter case checking still works:
function confirmEnding(str, target) {
return str.slice(-target.length)==target; //"==" is enough
}
Yes, the forum transforms quotes. To post code, you can use the </>
button on the forum’s editor.
Thank You for the hint!
You can also get rid of curly braces and return keyword btw:
const confirmEnding = (str, target) =>
str.substr(-target.length) == target;
Pretty cool and it works fine too!
But we have to define a function, not a constant (Restrictions on the input conditions).
It’s also a way to declare functions. It’s what’s usually called an arrow function, and has some differences with the usual function
declaration, but for the most part it works the same.
You can also define a function like this:
var confirmEnding = function(str, target) {...}
Thank You, guys, for the explanation!
confirmEnding=(str,target)=>str.substr(-target.length)==target;
I suppose that this is the shortest version which can pass the tests for this moment.
Guys, I offer to start a contest to make this code snippet shorter
confirmEnding=(a,b)=>a.substr(-b.length)==b;
Now if only the function name can be changed
Actually we can go shorter!
confirmEnding=(a,b)=>a.slice(-b.length)==b
confirmEnding=(a,b)=>a.substr(-b.length)==b;
This would also work, but you get to the point of being near unreadable
Edit…Damnit Kev
I already had this in mind when OP asked their question
depending on the next line, the semicolon is likely redundant.
Guys, You are awesome!
@lynxlynxlynx is correct.
Javascript compilers often put an inferred semi colon in there for you (you don’t see it in your code).
I have been reading the following book:
It covers some of the unusual (unique?) features of javascript, things that might not be intuitive and can lead to chasing ones tail (nuances?).
Cheers,
WWC
Do You have a used book
“More buying choices for
Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript (Effective Software Development Series) (Paperback)
by David Herman” for sale?