forked from benhoyt/countwords
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimized.js
53 lines (43 loc) · 1.01 KB
/
optimized.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
"use strict";
const rd = require("readline");
const dict = {};
function RefNum(num) {
this.num = num;
}
RefNum.prototype.toString = function () {
return this.num.toString();
};
const wordHandler = (word) => {
if (word.length === 0) return;
word = word.toLowerCase();
const item = dict[word];
if (item !== undefined) {
item.num++;
} else {
dict[word] = new RefNum(1);
}
};
const lineHandler = (line) => {
let lastIndex = 0;
while (true) {
const index = line.indexOf(" ", lastIndex);
if (index === -1) {
wordHandler(line.slice(lastIndex));
return;
}
wordHandler(line.slice(lastIndex, index));
lastIndex = index + 1;
}
};
const endHandler = () => {
const keys = Object.keys(dict);
keys.sort((a, b) => dict[b].num - dict[a].num);
process.stdout.write(keys.map((key) => `${key} ${dict[key].num}\n`).join(""));
};
rd.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
})
.on("line", lineHandler)
.on("close", endHandler);