-
Notifications
You must be signed in to change notification settings - Fork 26.2k
/
Copy pathstringify.ts
64 lines (54 loc) · 1.65 KB
/
stringify.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function stringify(token: any): string {
if (typeof token === 'string') {
return token;
}
if (Array.isArray(token)) {
return `[${token.map(stringify).join(', ')}]`;
}
if (token == null) {
return '' + token;
}
const name = token.overriddenName || token.name;
if (name) {
return `${name}`;
}
const result = token.toString();
if (result == null) {
return '' + result;
}
const newLineIndex = result.indexOf('\n');
return newLineIndex >= 0 ? result.slice(0, newLineIndex) : result;
}
/**
* Concatenates two strings with separator, allocating new strings only when necessary.
*
* @param before before string.
* @param separator separator string.
* @param after after string.
* @returns concatenated string.
*/
export function concatStringsWithSpace(before: string | null, after: string | null): string {
if (!before) return after || '';
if (!after) return before;
return `${before} ${after}`;
}
/**
* Ellipses the string in the middle when longer than the max length
*
* @param string
* @param maxLength of the output string
* @returns ellipsed string with ... in the middle
*/
export function truncateMiddle(str: string, maxLength = 100): string {
if (!str || maxLength < 1 || str.length <= maxLength) return str;
if (maxLength == 1) return str.substring(0, 1) + '...';
const halfLimit = Math.round(maxLength / 2);
return str.substring(0, halfLimit) + '...' + str.substring(str.length - halfLimit);
}