Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
ts 33 lines 1.31 KB
Raw
1 /** Type-level tuple of length `N`, used for arithmetic. */
2 type BuildTuple<N extends number, T extends unknown[] = []> = T['length'] extends N
3 ? T
4 : BuildTuple<N, [...T, unknown]>;
5
6 /** Type-level `A - B`, clamped to `0`. */
7 type Subtract<A extends number, B extends number> =
8 BuildTuple<A> extends [...BuildTuple<B>, ...infer Rest] ? Rest['length'] : 0;
9
10 /** Type-level `str.slice(0, N)`: first `N` characters of `S`. */
11 type Take<S extends string, N extends number, Acc extends unknown[] = []> = Acc['length'] extends N
12 ? ''
13 : S extends `${infer First}${infer Rest}`
14 ? `${First}${Take<Rest, N, [...Acc, unknown]>}`
15 : '';
16
17 /** Type-level result of truncating `S` to max `N` characters with `"..."` suffix. */
18 type Truncated<S extends string, N extends number> = `${Take<S, Subtract<N, 3>>}...`;
19
20 /** If `S` fits in `N` chars, return `S`; otherwise return the precise truncated literal. */
21 type TruncateResult<S extends string, N extends number> =
22 S extends Take<S, N> ? S : Truncated<S, N>;
23
24 /**
25 * Truncate a string to the given max length, appending "..." if truncated.
26 */
27 export function truncate<const S extends string, const N extends number>(
28 str: S,
29 max: N
30 ): TruncateResult<S, N> {
31 if (str.length <= max) return str as TruncateResult<S, N>;
32 return `${str.slice(0, max - 3)}...` as TruncateResult<S, N>;
33 }