Skip to content

Commit 976cc4e

Browse files
committed
Added simple string truncate with ellipsis method
1 parent 9d4d51a commit 976cc4e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

MADE.Data.Converters/src/string/index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,18 @@
1+
/**
2+
* Truncates a string value to the specified length with an ellipsis.
3+
* @param {string} value - The value to truncate.
4+
* @param {number} maxLength - The maximum length of the value.
5+
* @return {string} A truncated string with ellipsis if the value's length is greater than the max length.
6+
*/
7+
export function truncate(value: string, maxLength: number): string {
8+
if (isNullOrWhiteSpace(value) || value.length <= maxLength) {
9+
return value;
10+
}
11+
12+
const suffix = "...";
13+
return value.substring(0, maxLength - suffix.length) + suffix;
14+
}
15+
116
/**
217
* Converts a string value to a number value.
318
* @param {string} value - The string value to convert.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { truncate } from '../../src'
2+
3+
describe("when truncating a string", () => {
4+
it("should return a truncated string if greater than max length", () => {
5+
// Arrange
6+
const input = "Hello, World!"
7+
8+
// Act
9+
const result = truncate(input, 8);
10+
11+
// Assert
12+
expect(result).toBe("Hello...");
13+
});
14+
15+
it("should return original string if less than max length", () => {
16+
// Arrange
17+
const input = "Hello, World!"
18+
19+
// Act
20+
const result = truncate(input, input.length);
21+
22+
// Assert
23+
expect(result).toBe(input);
24+
});
25+
});

0 commit comments

Comments
 (0)