Repository navigation
Expand file tree
/
Copy pathutils.ts
More file actions
72 lines (60 loc) · 1.63 KB
/
Copy pathutils.ts
File metadata and controls
72 lines (60 loc) · 1.63 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
/**
* Utility functions providing Python-like data manipulation features.
*/
/**
* Combines multiple arrays into an array of tuples, stopping at the shortest length.
* Matches Python's built-in `zip()` behavior.
*/
export function zip<T extends any[]>(
...arrays: { [K in keyof T]: T[K][] }
): { [K in keyof T]: T[K] }[] {
if (arrays.length === 0) {
return [];
}
const minLength = Math.min(...arrays.map((arr) => arr.length));
const result: { [K in keyof T]: T[K] }[] = [];
for (let i = 0; i < minLength; i++) {
const tuple = arrays.map((arr) => arr[i]) as { [K in keyof T]: T[K] };
result.push(tuple);
}
return result;
}
/**
* Splits an array into smaller chunks of a specified maximum size.
*/
export function chunk<T>(array: T[], size: number): T[][] {
if (!Array.isArray(array) || size <= 0) {
return [];
}
const chunks: T[][] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
/**
* Generates an array of numbers over a specified sequence.
* Matches Python's built-in `range()` behavior.
*/
export function range(start: number, stop?: number, step = 1): number[] {
if (step === 0) {
throw new Error("Step argument must not be zero");
}
let actualStart = start;
let actualStop = stop;
if (actualStop === undefined) {
actualStop = start;
actualStart = 0;
}
const result: number[] = [];
if (step > 0) {
for (let i = actualStart; i < actualStop; i += step) {
result.push(i);
}
} else {
for (let i = actualStart; i > actualStop; i += step) {
result.push(i);
}
}
return result;
}