Back to Freecodecamp

Challenge 229: Truncate the Text 2

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69a890af247de743333bd4d2.md

latest2.5 KB
Original Source

--description--

Given a string, return a new string that is truncated so that the total width of the characters does not exceed 50 units.

Each character has a specific width:

LettersWidth
"ilI"1
"fjrt"2
"abcdeghkmnopqrstuvwxyzJL"3
"ABCDEFGHKMNOPQRSTUVWXYZ"4

The table above includes all upper and lower case letters. Additionally:

  • Spaces (" ") have a width of 2

  • Periods (".") have a width of 1

  • If the given string is 50 units or less, return the string as-is, otherwise

  • Truncate the string and add three periods at the end ("...") so it's total width, including the three periods, is as close as possible to 60 units without going over.

--hints--

truncateText("The quick brown fox") should return "The quick brown f...".

js
assert.equal(truncateText("The quick brown fox"), "The quick brown f...");

truncateText("The silky smooth sloth") should return "The silky smooth s...".

js
assert.equal(truncateText("The silky smooth sloth"), "The silky smooth s...");

truncateText("THE LOUD BRIGHT BIRD") should return "THE LOUD BRIG...".

js
assert.equal(truncateText("THE LOUD BRIGHT BIRD"), "THE LOUD BRIG...");

truncateText("The fast striped zebra") should return "The fast striped z...".

js
assert.equal(truncateText("The fast striped zebra"), "The fast striped z...");

truncateText("The big black bear") should return "The big black bear".

js
assert.equal(truncateText("The big black bear"), "The big black bear");

--seed--

--seed-contents--

js
function truncateText(str) {

  return str;
}

--solutions--

js
function truncateText(str) {
  const MAX_WIDTH = 50;
  const ELLIPSIS = "...";
  const ELLIPSIS_WIDTH = 3;
  const TRUNCATE_LIMIT = MAX_WIDTH - ELLIPSIS_WIDTH;

  const charGroups = {
    'ilI.': 1,
    'fjrt ': 2,
    'abcdeghkmnopqrstuvwxyzJL': 3,
    'ABCDEFGHKMNOPQRSTUVWXYZ': 4
  };

  function getCharWidth(char) {
    for (const key in charGroups) {
      if (key.includes(char)) return charGroups[key];
    }
    return 3;
  }

  function stringWidth(str) {
    let totalWidth = 0;
    for (const char of str) {
      totalWidth += getCharWidth(char);
    }
    return totalWidth;
  }

  if (stringWidth(str) <= MAX_WIDTH) return str;

  let result = "";
  let totalWidth = 0;

  for (const char of str) {
    const charWidth = getCharWidth(char);

    if (totalWidth + charWidth > TRUNCATE_LIMIT) break;

    result += char;
    totalWidth += charWidth;
  }

  return result + ELLIPSIS;
}