Skip to content

Commit bdce572

Browse files
committed
feat(utils): add utility function for truncating texts
1 parent 0fa6379 commit bdce572

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

packages/utils/src/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ export {
2727
pluralize,
2828
pluralizeToken,
2929
slugify,
30+
truncateDescription,
31+
truncateText,
32+
truncateTitle,
3033
} from './lib/formatting';
3134
export { getLatestCommit, git } from './lib/git';
3235
export {

packages/utils/src/lib/formatting.ts

+18
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { MAX_DESCRIPTION_LENGTH, MAX_TITLE_LENGTH } from '@code-pushup/models';
2+
13
export function slugify(text: string): string {
24
return text
35
.trim()
@@ -40,3 +42,19 @@ export function formatDuration(duration: number): string {
4042
}
4143
return `${(duration / 1000).toFixed(2)} s`;
4244
}
45+
46+
export function truncateText(text: string, maxChars: number): string {
47+
if (text.length <= maxChars) {
48+
return text;
49+
}
50+
const ellipsis = '...';
51+
return text.slice(0, maxChars - ellipsis.length) + ellipsis;
52+
}
53+
54+
export function truncateTitle(text: string): string {
55+
return truncateText(text, MAX_TITLE_LENGTH);
56+
}
57+
58+
export function truncateDescription(text: string): string {
59+
return truncateText(text, MAX_DESCRIPTION_LENGTH);
60+
}

packages/utils/src/lib/formatting.unit.test.ts

+19
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
pluralize,
66
pluralizeToken,
77
slugify,
8+
truncateText,
89
} from './formatting';
910

1011
describe('slugify', () => {
@@ -78,3 +79,21 @@ describe('formatDuration', () => {
7879
expect(formatDuration(ms)).toBe(displayValue);
7980
});
8081
});
82+
83+
describe('truncateText', () => {
84+
it('should replace overflowing text with ellipsis', () => {
85+
expect(truncateText('All work and no play makes Jack a dull boy', 32)).toBe(
86+
'All work and no play makes Ja...',
87+
);
88+
});
89+
90+
it('should produce truncated text which fits within limit', () => {
91+
expect(
92+
truncateText('All work and no play makes Jack a dull boy', 32).length,
93+
).toBeLessThanOrEqual(32);
94+
});
95+
96+
it('should leave text unchanged when within character limit', () => {
97+
expect(truncateText("Here's Johnny!", 32)).toBe("Here's Johnny!");
98+
});
99+
});

0 commit comments

Comments
 (0)