-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcut.js
More file actions
executable file
·89 lines (75 loc) · 2.12 KB
/
cut.js
File metadata and controls
executable file
·89 lines (75 loc) · 2.12 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
#! /usr/bin/env node
const fs = require("fs");
const readline = require("readline");
const getFields = async ({ file, indices, delimiter }) => {
if (file === "-" || !fs.existsSync(file)) stream = process.stdin;
else {
stream = fs.createReadStream(file);
}
return new Promise((resolve) => {
const rl = readline.createInterface({
input: stream,
output: undefined,
terminal: false,
});
const res = [];
rl.on("line", function (line) {
//split each line by delimiter
const fields = line.split(delimiter);
// list of fields to be printed out
let requiredFields = [];
for (let index of indices) {
requiredFields.push(fields[index - 1]);
}
res.push(requiredFields);
});
rl.on("close", function () {
resolve(res);
});
});
};
const getOptionFileAndIndices = (args, optionPosition, filePosition) => {
let indices;
const lists = args[optionPosition].slice(2);
let seperator = " ";
if (lists.includes(",")) seperator = ",";
indices = lists.split(seperator).map((index) => parseInt(index));
return [args[optionPosition].slice(0, 2), args[filePosition], indices];
};
async function main() {
const args = process.argv;
const validOptions = new Set(["-f"]);
var option,
file,
indices = [];
// default to tab
let delimiter = "\t";
for (let i = args.length - 1; i >= 2; i--) {
if (validOptions.has(args[i].slice(0, 2))) {
[option, file, indices] = getOptionFileAndIndices(
args,
i,
args.length - 1
);
}
if (args[i].slice(0, 2) === "-d") delimiter = args[i].slice(2);
}
const logResult = async (operation, file, indices, delimiter) => {
const res = await operation({ file, indices, delimiter });
for (let portion of res) {
//Output fields are separated by the delimiter character
console.log(portion.join(delimiter));
}
};
switch (option) {
case "-f": {
logResult(getFields, file, indices, delimiter);
break;
}
default:
return;
}
}
main()
.then()
.catch((e) => console.error("No such file or invalid option"));