2.6 KiB
id, title, challengeType, dashedName
| id | title | challengeType | dashedName |
|---|---|---|---|
| 69a890af247de743333bd4d2 | Challenge 229: Truncate the Text 2 | 28 | challenge-229 |
--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:
| Letters | Width |
|---|---|
"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 its total width, including the three periods, is as close as possible to 50 units without going over.
--hints--
truncateText("The quick brown fox") should return "The quick brown f...".
assert.equal(truncateText("The quick brown fox"), "The quick brown f...");
truncateText("The silky smooth sloth") should return "The silky smooth s...".
assert.equal(truncateText("The silky smooth sloth"), "The silky smooth s...");
truncateText("THE LOUD BRIGHT BIRD") should return "THE LOUD BRIG...".
assert.equal(truncateText("THE LOUD BRIGHT BIRD"), "THE LOUD BRIG...");
truncateText("The fast striped zebra") should return "The fast striped z...".
assert.equal(truncateText("The fast striped zebra"), "The fast striped z...");
truncateText("The big black bear") should return "The big black bear".
assert.equal(truncateText("The big black bear"), "The big black bear");
--seed--
--seed-contents--
function truncateText(str) {
return str;
}
--solutions--
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;
}