Tom 17a55c6e18
fix(curriculum): Consolidated comments for JavaScript Algorithms and Data Structures challenges - part 1 of 4 (#38258)
* fix: consolidate/remove comments

* fix: remove => from comment

* fix: reverted changes to add same changes to another PR

* fix: removed 'the' from sentence

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

* fix: removed 'the' from the sentence

Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>

Co-authored-by: Oliver Eyton-Williams <ojeytonwilliams@gmail.com>
2020-03-04 13:08:54 -06:00

2.4 KiB

id, title, isRequired, challengeType, forumTopicId
id title isRequired challengeType forumTopicId
ac6993d51946422351508a41 Truncate a String true 5 16089

Description

Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a ... ending.

Instructions

Tests

tests:
  - text: <code>truncateString("A-tisket a-tasket A green and yellow basket", 8)</code> should return "A-tisket...".
    testString: assert(truncateString("A-tisket a-tasket A green and yellow basket", 8) === "A-tisket...");
  - text: <code>truncateString("Peter Piper picked a peck of pickled peppers", 11)</code> should return "Peter Piper...".
    testString: assert(truncateString("Peter Piper picked a peck of pickled peppers", 11) === "Peter Piper...");
  - text: <code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)</code> should return "A-tisket a-tasket A green and yellow basket".
    testString: assert(truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length) === "A-tisket a-tasket A green and yellow basket");
  - text: <code>truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)</code> should return "A-tisket a-tasket A green and yellow basket".
    testString: assert(truncateString('A-tisket a-tasket A green and yellow basket', 'A-tisket a-tasket A green and yellow basket'.length + 2) === 'A-tisket a-tasket A green and yellow basket');
  - text: <code>truncateString("A-", 1)</code> should return "A...".
    testString: assert(truncateString("A-", 1) === "A...");
  - text: <code>truncateString("Absolutely Longer", 2)</code> should return "Ab...".
    testString: assert(truncateString("Absolutely Longer", 2) === "Ab...");

Challenge Seed

function truncateString(str, num) {
  return str;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

Solution

function truncateString(str, num) {
  if (num >= str.length) {
    return str;
  }

  return str.slice(0, num) + '...';
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);