|
1 | | -var _ = require('lodash'); |
2 | | -var Console = require('console').Console; |
| 1 | +"use strict"; |
| 2 | +var readline = require('readline'); |
| 3 | +var TimSort = require('timsort'); |
3 | 4 |
|
4 | | -var data = {}; |
| 5 | +process.stdin.setEncoding('utf8'); |
5 | 6 |
|
6 | | -var log = new Console(process.stderr, process.stderr); |
| 7 | +let rl = readline.createInterface({ input: process.stdin, terminal: false }); |
| 8 | +let wordCounts = {}; |
| 9 | +const regExp = /[ \t\n\r]+/g; |
7 | 10 |
|
8 | | -process.stdin.setEncoding('utf8'); |
9 | | -process.stdin.on('readable', function() { |
10 | | - var chunk = process.stdin.read(); |
11 | | - if (chunk !== null) { |
12 | | - _.forEach(chunk.split(/[\n\t\r\f ]+/g), function(word) { |
13 | | - if (word == '') {return;} |
14 | | - if (data[word]) { |
15 | | - //console.log('Adding to ' + word + '.'); |
16 | | - data[word].count++; |
17 | | - } else { |
18 | | - //console.log('Inserting ' + word + '.'); |
19 | | - data[word] = {word: word, count: 1}; |
20 | | - } |
21 | | - }); |
| 11 | +rl.on('line', (line) => { |
| 12 | + let words = line.trim().split(regExp); |
| 13 | + |
| 14 | + for(let i = 0, len = words.length; i < len; i++) { |
| 15 | + let word = words[i]; |
| 16 | + |
| 17 | + if (!word) |
| 18 | + return; |
| 19 | + |
| 20 | + if(wordCounts.hasOwnProperty(word)) { |
| 21 | + wordCounts[word]++; |
| 22 | + } |
| 23 | + else { |
| 24 | + wordCounts[word] = 1; |
| 25 | + } |
22 | 26 | } |
23 | | -}); |
| 27 | +}).on('close', () => { |
| 28 | + let wordList = Object.keys(wordCounts); |
| 29 | + |
| 30 | + let compare = (x, y) => { |
| 31 | + if(wordCounts[x] < wordCounts[y]) |
| 32 | + return 1; |
24 | 33 |
|
25 | | -process.stdin.on('end', function() { |
26 | | - var sorted = _.sortByOrder(data, ['count', 'word'], ['desc', 'asc']); |
27 | | - //console.log('Output has '+sorted.length+' items:'); |
28 | | - _.forEach(sorted, function(item){ |
29 | | - process.stdout.write(item.word + '\t' + item.count + '\n'); |
30 | | - }); |
| 34 | + if(wordCounts[x] === wordCounts[y] && x > y) |
| 35 | + return 1; |
| 36 | + |
| 37 | + return -1; |
| 38 | + } |
| 39 | + |
| 40 | + TimSort.sort(wordList, compare); |
| 41 | + |
| 42 | + let word = ''; |
| 43 | + let count = ''; |
| 44 | + let buff = ''; |
| 45 | + const maxBuff = 1000; |
| 46 | + for(let i = 0, len = wordList.length; i < len; i++) { |
| 47 | + word = wordList[i]; |
| 48 | + count = wordCounts[word]; |
| 49 | + |
| 50 | + buff += word + '\t' + count + '\n'; |
| 51 | + if (i % maxBuff === 0) { |
| 52 | + process.stdout.write(buff); |
| 53 | + buff = ''; |
| 54 | + } |
| 55 | + } |
| 56 | + process.stdout.write(buff); |
| 57 | + process.exit(0); |
31 | 58 | }); |
0 commit comments