Repository navigation
Expand file tree
/
Copy patharray.ts
More file actions
63 lines (59 loc) · 1.9 KB
/
Copy patharray.ts
File metadata and controls
63 lines (59 loc) · 1.9 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
/**
* Returns the index of the last element in the array where predicate is true, and -1
* otherwise.
* @param array The source array to search in
* @param predicate find calls predicate once for each element of the array, in descending
* order, until it finds one where predicate returns true. If such an element is found,
* findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
*/
export function findLastIndex<T>(
array: Array<T>,
predicate: (value: T, index: number, obj: T[]) => boolean,
): number {
let l = array.length;
while (l--) {
const item = array[l];
if (item !== undefined && predicate(item, l, array)) {
return l;
}
}
return -1;
}
export function findLast<T>(
array: Array<T>,
predicate: (value: T, index: number, obj: T[]) => boolean,
): T | undefined {
const index = findLastIndex(array, predicate);
return index === -1 ? undefined : array[index];
}
/**
* Converts a partial or complete stringified array into an actual array.
* Handles both complete JSON strings and incomplete array strings.
* Splits on the specific tokens: [" ", " "]
* @param arrayString A string representation of an array, which may be incomplete
* @returns Array of strings parsed from the input
*/
export function parsePartialArrayString(arrayString: string): string[] {
try {
// Try parsing as complete JSON first
return JSON.parse(arrayString);
} catch {
// If JSON parsing fails, handle as partial string
const trimmed = arrayString.trim();
if (!trimmed.startsWith('["')) {
return [];
}
// Remove leading ["
let content = trimmed.slice(2);
// Remove trailing "] if it exists
content = content.replace(/"]$/, "");
if (!content) {
return [];
}
// Split on ", " token and handle the parts
return content
.split('", "')
.map((item) => item.trim())
.filter(Boolean);
}
}