My low bro solution, it's ugly, and still took me time...
function truncate(str, num) {
if(num <= 3){
return str.slice(0,num) + "...";
}
if(str.length > num){
return str.slice(0,num-3) + "...";
}
if(num >= str.length){
return str;
}
}
truncate("A-tisket a-tasket A green and yellow basket", 2);
It took me time because I literally translated this instructions "If the length of the string is less than or equal to 3 characters" as this:
if(str.length <= 3){
return str.slice(0,num) + "...";
}
instead of course, of this:
if(num <= 3){
return str.slice(0,num) + "...";
}
akshat01 posted this on Gitter in the HelpBonfires room and it's way more concise:
function truncate(str, num) {
var i= 0;
if (num >=3){
i=3;
}
if (str.length> num){
str= str.slice(0,num-i)+"...";}
return str;
}
truncate("A-tisket a-tasket A green and yellow basket", 1);
I don't know what it says about me but it took me a good 15 mins to understand the logic of just returning the str as is, in fact the default value since both "if" statements covered all other cases
No comments:
Post a Comment