-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathjoinToString.ts
More file actions
77 lines (67 loc) · 1.89 KB
/
Copy pathjoinToString.ts
File metadata and controls
77 lines (67 loc) · 1.89 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
import Sequence from "./Sequence";
export interface JoinConfig<T> {
value?: string;
separator?: string;
prefix?: string;
postfix?: string;
limit?: number;
truncated?: string;
transform?: (value: T) => string;
}
const defaults = {
value: "",
separator: ", ",
prefix: "",
postfix: "",
limit: -1,
truncated: "...",
transform: undefined
};
export class JoinToString {
/**
* Joins all elements of the sequence into a string with the given configuration.
*
* @param {JoinConfig<T>} config
* @returns {string}
*/
joinToString<T>(this: Sequence<T>, config: JoinConfig<T> = defaults): string {
const {
value = defaults.value,
separator = defaults.separator,
prefix = defaults.prefix,
postfix = defaults.postfix,
limit = defaults.limit,
truncated = defaults.truncated,
transform = defaults.transform
} = config;
let result = `${value}${prefix}`;
let count = 0;
for (let item = this.iterator.next(); !item.done; item = this.iterator.next()) {
count++;
if (count > 1) {
result += separator;
}
if (limit < 0 || count <= limit) {
result += transform != null
? transform(item.value)
: String(item.value);
} else {
break;
}
}
if (limit >= 0 && count > limit) {
result += truncated;
}
result += postfix;
return result;
}
/**
* Joins all elements of the sequence into a string with the given configuration.
*
* @param {JoinConfig<T>} config
* @returns {string}
*/
joinTo<T>(this: Sequence<T>, config: JoinConfig<T> = defaults): string {
return this.joinToString(config);
}
}