From ec3c251db0aff2beefdc15eb745f27792c253aba Mon Sep 17 00:00:00 2001 From: sergeyp Date: Fri, 22 May 2020 20:03:37 +0300 Subject: [PATCH] Node js version Inspired by C# version of komrad MblSH --- bench.py | 1 + src/freq01.js | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/freq01.js diff --git a/bench.py b/bench.py index 0841030..ab2a527 100755 --- a/bench.py +++ b/bench.py @@ -18,6 +18,7 @@ def run1(args, src_name, num_runs): runs = [ [['java', '-jar', './bin/freq01scala.jar'], 'freq01.scala', 3], [['python', './src/freq01.py'], 'freq01.py', 3], + [['node', './src/freq01.js'], 'freq01.js', 3], [['./bin/freq03cpp' + EXE], 'freq03.cpp'], [['./bin/freq02cpp' + EXE], 'freq02.cpp'], [['./bin/freq01cpp' + EXE], 'freq01.cpp'], diff --git a/src/freq01.js b/src/freq01.js new file mode 100644 index 0000000..d198b9b --- /dev/null +++ b/src/freq01.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const dict = new Map(); +function addWord(word) { + const val = dict.get(word); + if (val) + dict.set(word, val + 1); + else + dict.set(word, 1); +} +function isLetter(code) { + return code > 64 && code < 91 + || code > 96 && code < 123; +} +function writeFile(filePath) { + const fstream = fs.createWriteStream(filePath); + const out = Array.from(dict.entries()).sort((kv1, kv2) => { + if (kv1[1] < kv2[1]) { + return 1; + } + else if (kv1[1] == kv2[1]) { + return kv1[0] > kv2[0] ? 1 : -1; + } + else { + return -1; + } + }); + try { + for (let i = 0; i < out.length; i++) { + fstream.write(out[i][1] + " " + out[i][0] + "\n"); + } + } + finally { + fstream.close(); + } +} +function main(args) { + if (args.length != 4) + return; + const start = (new Date()).getTime(); + let word = ""; + const stream = fs.createReadStream(args[2]); + stream.on('readable', () => { + let data; + while (null !== (data = stream.read())) { + for (let i = 0; i < data.length; i++) { + const ch = data[i]; + if (isLetter(ch)) { + word += String.fromCharCode(ch); + ; + continue; + } + if (word.length == 0) + continue; + addWord(word.toLowerCase()); + word = ""; + } + } + }); + stream.on('end', () => { + if (word.length > 0) + addWord(word.toLowerCase()); + writeFile(args[3]); + console.log(`Time ${(new Date()).getTime() - start} ms`); + }); +} +main(process.argv); +//# sourceMappingURL=app.js.map \ No newline at end of file