Skip to content

Instantly share code, notes, and snippets.

@ricardobeat
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricardobeat/ee2fb2a6d704205446b7 to your computer and use it in GitHub Desktop.
Save ricardobeat/ee2fb2a6d704205446b7 to your computer and use it in GitHub Desktop.
compiling chess results with node streams
#!/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)
}
})
})
@lucaspottersky
Copy link

i think you got a copy & paste error at Line 14 d:-) cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment