-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
90 lines (82 loc) · 1.84 KB
/
index.ts
File metadata and controls
90 lines (82 loc) · 1.84 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
78
79
80
81
82
83
84
85
86
87
88
89
90
import * as fs from "node:fs";
import * as readline from "node:readline";
/**
* Represents a node in the TSP file.
*/
interface Node {
id: number;
x: number;
y: number;
}
/**
* Represents a TSP file.
*/
interface TspFile {
name?: string;
comment?: string;
type?: string;
dimension?: number;
edgeWeightType?: string;
nodes: Node[];
}
/**
* Reads a TSP file and extracts its contents.
*/
export const readTspFile = async (filePath: string): Promise<TspFile> => {
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
let parsingNodes = false;
let name: string | undefined;
let comment: string | undefined;
let type: string | undefined;
let dimension: number | undefined;
let edgeWeightType: string | undefined;
const nodes: Array<Node> = [];
for await (const line of rl) {
const trimmed = line.trim();
if (!trimmed || trimmed === "EOF") continue;
if (trimmed === "NODE_COORD_SECTION") {
parsingNodes = true;
continue;
}
if (parsingNodes) {
const [idStr, xStr, yStr] = trimmed.split(/\s+/);
nodes.push({
id: parseInt(idStr),
x: parseFloat(xStr),
y: parseFloat(yStr),
});
} else {
const [key, ...rest] = trimmed.split(":");
const value = rest.join(":").trim();
switch (key.trim()) {
case "NAME":
name = value;
break;
case "COMMENT":
comment = value;
break;
case "TYPE":
type = value;
break;
case "DIMENSION":
dimension = parseInt(value);
break;
case "EDGE_WEIGHT_TYPE":
edgeWeightType = value;
break;
}
}
}
return {
name,
comment,
type,
dimension,
edgeWeightType,
nodes,
};
};