Skip to content

Commit 2bbb2d4

Browse files
author
Matej Szendi
committed
* Add action truncate()
1 parent 512bca2 commit 2bbb2d4

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ const UsernameSchema = tb.pipe(tb.string(), tb.trim());
120120
| | `trim()` - Removes whitespace from both ends | |
121121
| | `trimEnd()` - Removes whitespace from the end | |
122122
| | `trimStart()` - Removes whitespace from the start | |
123+
| | `truncate()` - Shortens a string to a specified maximum length with an optional suffix | |
123124

124125
These actions can be chained and combined as needed using `pipe()` function to create complex transformation schemas for converting and processing input data.
125126

src/actions/truncate.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import type { Action } from "../types.ts";
2+
3+
export type TruncateAction = Action<string | null, string | null>;
4+
5+
export function truncate(maxLength: number, suffix = "..."): TruncateAction {
6+
return (input) => {
7+
if (input === null) {
8+
return null;
9+
}
10+
11+
if (input.length <= maxLength) {
12+
return input;
13+
}
14+
15+
return input.substring(0, maxLength) + suffix;
16+
};
17+
}

0 commit comments

Comments
 (0)