Skip to content

Instantly share code, notes, and snippets.

@jnjosh
Forked from artlung/challege1.js
Created September 20, 2010 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnjosh/587495 to your computer and use it in GitHub Desktop.
Save jnjosh/587495 to your computer and use it in GitHub Desktop.
var fs = require("fs");
var file = "file.txt",
sum = 0,
chars = [];
/// @summary: aggregate values
function aggregater(value) {
if (parseInt(value, 10).toString() === value.toString()) {
sum += parseInt(value, 10);
return;
}
chars[value] = typeof(chars[value]) === 'undefined' ? 1 : chars[value] + 1;
}
/// @summary: print values
function printer() {
console.log("Sum = " + sum);
for (i in chars)
if (chars.hasOwnProperty(i)) console.log(i + ' = ' + chars[i]);
}
// create stream
var stream = fs.createReadStream(file, {
'flags': 'r'
, 'encoding': 'utf8'
, 'mode': 0666
, 'bufferSize': 2
});
// @summary: listen for incoming data to aggregate
stream.addListener("data", function(data) {
aggregater(data.toString().replace("\n", ""));
});
// @summary: file done streaming, print results
stream.addListener("end", function() {
printer();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment