Skip to content

Commit 9268f43

Browse files
feat: add string truncate algorithm
1 parent 5c39e87 commit 9268f43

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

‎String/Truncate.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* @function truncate
3+
* @description Truncates a string to a specified length and appends
4+
* an ellipsis (...) if the string exceeds that length.
5+
* @param {string} str - The input string
6+
* @param {number} maxLength - The maximum length of the output string
7+
* @returns {string} - The truncated string
8+
* @see https://en.wikipedia.org/wiki/Ellipsis
9+
* @example truncate("Hello World", 5) => "Hello..."
10+
* @example truncate("Hi", 5) => "Hi"
11+
* @example truncate("Hello World", 11) => "Hello World"
12+
*/
13+
const truncate = (str, maxLength) => {
14+
if (typeof str !== 'string') {
15+
throw new TypeError('First argument must be a string')
16+
}
17+
if (!Number.isInteger(maxLength) || maxLength < 1) {
18+
throw new TypeError('Second argument must be a positive integer')
19+
}
20+
return str.length > maxLength ? str.slice(0, maxLength) + '...' : str
21+
}
22+
23+
export { truncate }

‎String/test/Truncate.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { truncate } from '../Truncate.js'
2+
3+
describe('truncate', () => {
4+
test("truncate('Hello World', 5) returns 'Hello...'", () => {
5+
expect(truncate('Hello World', 5)).toBe('Hello...')
6+
})
7+
8+
test("truncate('Hi', 5) returns 'Hi'", () => {
9+
expect(truncate('Hi', 5)).toBe('Hi')
10+
})
11+
12+
test('truncate at exact length returns original', () => {
13+
expect(truncate('Hello', 5)).toBe('Hello')
14+
})
15+
16+
test("truncate('Hello World', 11) returns 'Hello World'", () => {
17+
expect(truncate('Hello World', 11)).toBe('Hello World')
18+
})
19+
20+
test('truncate empty string returns empty string', () => {
21+
expect(truncate('', 5)).toBe('')
22+
})
23+
24+
test('truncate with maxLength 1', () => {
25+
expect(truncate('Hello', 1)).toBe('H...')
26+
})
27+
28+
test('truncate long string', () => {
29+
expect(truncate('The quick brown fox', 9)).toBe('The quick...')
30+
})
31+
32+
test('throws TypeError for non-string input', () => {
33+
expect(() => truncate(123, 5)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for zero maxLength', () => {
37+
expect(() => truncate('Hello', 0)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for negative maxLength', () => {
41+
expect(() => truncate('Hello', -1)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float maxLength', () => {
45+
expect(() => truncate('Hello', 2.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)