If the code passes the tests everything is fine. Code works, you are done.
But anyway, I would like to show off a little 
You don’t need the last else if
statement.
You don’t have to create result
variables.
Code
function truncateString(str, num) {
if (str.length > num && num>4) {
return str.slice(-str.length, num-3)+ "...";
} else if (num <4) {
return str.slice(-str.length, num)+"...";
}
return str;
}
Now we see that both return
statements are almost the same. Lets move the return statement outside the if
s and in if
statements we will set the parts that change:
Code
function truncateString(str, num) {
var cut = 0,
dots = '';
if (str.length > num && num>4) {
cut = 3;
dots = '...';
} else if (num <4) {
dots = '...';
}
return str.slice(-str.length, num - cut) + dots;
}
Well, we have both times set dots
to '...'
. Actually we need dots only if we change the input string, and we change the input string if it is longer than num
. So if string is less or equal to num
we can instantly return:
Code
function truncateString(str, num) {
if (str.length <= num) return str;
var cut = 0;
if (num>4) {
cut = 3;
} else if (num <4) {
}
return str.slice(-str.length, num - cut) + '...';
}
Now we have an empty else
, let’s throw it away:
Code
function truncateString(str, num) {
if (str.length <= num) return str;
var cut = 0;
if (num>4) {
cut = 3;
}
return str.slice(-str.length, num - cut) + '...';
}
Then there is such thing as ternary operator, you can write if...else
in one line: :
Code
function truncateString(str, num) {
if (str.length <= num) return str;
var cut = num > 4 ? 3 : 0;
return str.slice(-str.length, num - cut) + '...';
}
And so on…
Btw, -str.length
is 0
:nerd:
function truncateString(str, num) {
return str.length <= num ? str : str.slice(0, num <= 3 ? num : num - 3) + '...';
}