-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathuniq.ts
99 lines (84 loc) · 1.98 KB
/
uniq.ts
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
91
92
93
94
95
96
97
98
99
import fs from 'fs';
/**
* Input Interface for uniq function
*
* @interface IUniqInput
* @typedef {IUniqInput}
*/
interface IUniqInput {
path?: string;
inStream?: NodeJS.ReadStream | fs.ReadStream;
count?: boolean;
repeated?: boolean;
unique?: boolean;
}
/**
* This function Reads the given stream and returns a Buffer.
*
* @async
* @param {NodeJS.ReadStream} stream
* @returns {Promise<Buffer>}
*/
async function readStream(
stream: NodeJS.ReadStream | fs.ReadStream
): Promise<Buffer> {
const chunks = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
async function uniq({
path,
inStream,
count = false,
repeated = false,
unique = false
}: IUniqInput): Promise<string> {
if (repeated && unique) {
throw new Error('Both -u and -d option cannot be present');
}
let input = '';
if (path !== undefined) {
input = fs.readFileSync(path).toString().trim();
} else if (inStream !== undefined) {
input = (await readStream(inStream)).toString();
} else {
throw new Error('No file or stream provided');
}
const lines = input.split(/\r\n|\r|\n/);
const uniqLines = new Map<string, number>();
lines.forEach((line) => {
if (uniqLines.has(line)) {
uniqLines.set(line, uniqLines.get(line)! + 1);
} else {
uniqLines.set(line, 1);
}
});
const output: string[] = [];
uniqLines.forEach((value, key) => {
// We are checking for the various parameters
// and pushing the relevant string into the output array.
if (unique && value === 1 && !count) {
output.push(key);
return;
}
if (unique && value === 1 && count) {
output.push(`${value} ${key}`);
return;
}
if (unique && value > 1) {
return;
}
if (repeated && value <= 1) {
return;
}
if (count) {
output.push(`${value} ${key}`);
return;
}
output.push(key);
});
return output.join('\n');
}
export { uniq };