"Truncate a string" challenge with only one IF


Not sure if it is of any interest to anybody, but I decided to pass the “Truncate a string” challenge using only one IF and I just succeeded! It took some time to figure out the math formula, but I did! And I’m happy, so I just decided to share it. :slight_smile:

function truncateString(str, num) {
// Clear out that junk in your trunk
if (num<str.length) {
str = str.slice(0,-str.length+num-Math.min(3,Math.max(0,num*(num-3/Math.abs(num-3)))));
str += "...";
return str;

Just to remember, the challenge was to truncate any str argument if its length passed the num argument, and append three dots on the string, still respecting the num limit.

The tricky part was that if num was 3 or less,the three dots append could pass the num limit, only the truncated string should match the num limit.


Well done! It’s easy to forget how useful those math functions are.

what about this solution?:

function truncateString(str, num) {
  var ausgabe = "";
  return (str.slice(str, num) < str) ? str.slice(str, num) + "..." : str.slice(str, num);