Last active
August 29, 2015 14:13
-
-
Save ricardobeat/ee2fb2a6d704205446b7 to your computer and use it in GitHub Desktop.
compiling chess results with node streams
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
#!/usr/bin/env node | |
var fs = require('fs') | |
var path = require('path') | |
var dir = process.argv[2] | |
if (!dir) throw new Error('Usage: ./chess.js path-to-pgn-files/ ') | |
var white = 0 | |
var black = 0 | |
var ties = 0 | |
var rw = /Result\s"1-0"/g | |
var rb = /Result\s"1-0"/g | |
var rt = /Result\s"1\/2-1\/2"/g | |
var files = fs.readdirSync(dir) | |
var closed = 0 | |
var total = files.length | |
console.time('Processed ' + total + ' files') | |
files.forEach(function (file) { | |
var stream = fs.createReadStream(path.join(dir, file)) | |
stream.setEncoding('utf8') | |
stream.on('readable', function () { | |
var chunk, match | |
while ((chunk = stream.read()) !== null) { | |
while (rw.exec(chunk)) white += 1 | |
while (rb.exec(chunk)) black += 1 | |
while (rt.exec(chunk)) ties += 1 | |
} | |
}) | |
stream.on('close', function () { | |
console.log('Processed %s', file) | |
if (++closed == total) { | |
console.timeEnd('Processed ' + total + ' files') | |
console.log("white: %d, black: %d, ties: %d", white, black, ties) | |
} | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i think you got a copy & paste error at Line 14 d:-) cheers