-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
78 lines (60 loc) · 2.27 KB
/
index.js
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
const path = require("path");
const groupJson = require("./utils/utils").groupJson;
const loadCsvToJson = require("./utils/loadCsv").loadCsv;
const poolSize = require("./config").poolSize;
const WorkerPool = require("./workers/workerPool");
const saveJsonToCsv = require("./utils/saveJsonToCsv").saveJsonToCsv;
const csvFilePath = require("./config").csvFilePath;
const outputFile = require("./config").outputFile;
async function run() {
try {
//load csv from file and convert to json
const jsonArray = await loadCsvToJson(csvFilePath);
//group json by vehicle_id
const groupedMap = groupJson(jsonArray, "vehicle_id");
//create new worker pool
const pool = new WorkerPool(path.join(__dirname, "workers", "worker.js"), poolSize);
let dataForCsv = [];
for ([mapKey, mapValue] of groupedMap) {
if (mapValue && mapValue.length < 2) {
mapValue[0].distance_from_prev_point = 0;
mapValue[0].worker_id = -1;
groupedMap.set(mapKey, mapValue);
} else {
mapValue.sort((a, b) => {
return a.row_id - b.row_id;
});
mapValue[0].distance_from_prev_point = 0;
mapValue[0].worker_id = -1;
groupedMap.set(mapKey, mapValue);
const dataForWork = [];
for (let i = 1; i < mapValue.length; i++) {
//make data for worker
dataForWork.push([mapValue[i - 1], mapValue[i]]);
//send data to workers
await Promise.all(
dataForWork.map(async (value, i) => {
const workerResult = await pool.run(() => value);
//update map json data by recieved data from worker
mapValue[i + 1] = workerResult;
groupedMap.set(mapKey, mapValue);
})
);
}
}
//concat data for csv
dataForCsv = dataForCsv.concat(...groupedMap.get(mapKey));
}
//csv convert options
const fieldsForJsonToCsv = ["row_id", "vehicle_id", "latitude", "longitude", "distance_from_prev_point", "worker_id"];
const csvOpts = { fieldsForJsonToCsv };
//convert csv to json and save to file
await saveJsonToCsv(dataForCsv, csvOpts, outputFile);
console.log("Process Done!");
process.exit(0);
} catch (e) {
console.error(e);
process.exit(-1);
}
}
run();