-
Notifications
You must be signed in to change notification settings - Fork 39
/
strutil.ts
57 lines (50 loc) 路 1.45 KB
/
strutil.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
export const trimNonAlphaNum = (str: string) => {
return str.replace(/^\W+|\W+$/g, '');
};
export const splitIntoTwo = (
str: string,
separator: Readonly<RegExp | string>
): string[] => {
const index = str.search(separator);
if (index === -1) {
return [str]; // No separator found, return the original string as the only part
}
const matchResult = str.match(separator);
if (!matchResult) {
throw new Error('Match failed unexpectedly.');
}
const firstPart = str.substring(0, index);
const secondPart = str.substring(index + matchResult[0].length);
return [firstPart, secondPart];
};
export const dedup = (seq: readonly string[]): string[] => {
const seen = new Set<string>();
const result: string[] = [];
for (const x of seq) {
if (!seen.has(x)) {
seen.add(x);
result.push(x);
}
}
return result;
};
export const extractIdAndText = (
input: string
): { id: number; text: string } => {
const match = input.match(/^(\d+)[.,\s]+(.*)$/);
if (!match || match.length < 3) {
throw new Error(
'line must start with a number, a dot and then text. e.g. "1. hello"'
);
}
const id = parseInt(match[1] as string, 10);
const text = (match[2] as string).trim();
return { id, text };
};
export const batchArray = <T>(arr: readonly T[], size: number): T[][] => {
const chunkedArr = [];
for (let i = 0; i < arr.length; i += size) {
chunkedArr.push(arr.slice(i, i + size));
}
return chunkedArr;
};