Created
September 23, 2014 11:58
-
-
Save piglovesyou/a930ea484f764ec1b9ec to your computer and use it in GitHub Desktop.
read/write stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var readable = fs.createReadStream('large.txt', {encoding: 'utf8'}); | |
var writable = fs.createWriteStream('out.txt', {encoding: 'utf8'}); | |
var count; | |
var left = ''; | |
var reader = new Reader; | |
readable.on('data', function(chunk) { | |
reader.set(chunk); | |
if (count == null) { | |
count = reader.read(); | |
} | |
var line; | |
while (line = reader.read()) { | |
if (line.length < 9) { | |
break; | |
} | |
var pair = line.split(' '); | |
var out = rate(pair[0], pair[1]); | |
writable.write(out.H + 'H' + out.B + 'B\n'); | |
} | |
}); | |
function Reader() { | |
this.chunk = ''; | |
this.needle = 0; | |
} | |
Reader.prototype.set = function(chunk) { | |
this.chunk = this.chunk.slice(this.needle) + chunk; | |
this.needle = 0; | |
}; | |
Reader.prototype.read = function() { | |
var curr = this.chunk.indexOf('\n', this.needle); | |
var rv = this.chunk.slice(this.needle, curr); | |
this.needle = curr + 1; | |
return rv; | |
}; | |
function rate(secret, answer) { | |
return answer.split('').reduce(function(rv, num, j) { | |
if (num == secret[j]) { | |
++rv.H; | |
} else if (~secret.indexOf(num)) { | |
++rv.B; | |
} | |
return rv; | |
}, {H: 0, B: 0}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment