Last active
April 7, 2018 23:35
-
-
Save Jimbly/14f856cdfc8f323a48fa5752960d2be9 to your computer and use it in GitHub Desktop.
Simplified GoogleCodeJam Javascript stdio tokenizer
This file contains hidden or 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
| 'use strict'; | |
| // Does not work on Google's servers, try stdio-async instead | |
| const fs = require('fs'); | |
| let tok = (function () { | |
| let buffer = Buffer.alloc(1); | |
| function getc() { | |
| while (true) { | |
| try { | |
| let bytes_read = fs.readSync(process.stdin.fd, buffer, 0, 1); | |
| if (bytes_read) { | |
| return buffer.toString(); | |
| } else { | |
| return null; | |
| } | |
| } catch (e) { | |
| if (e.code !== 'EAGAIN') { | |
| throw e; | |
| } | |
| // this exception happens when exhausting the buffer on Linux, with e.code === 'EAGAIN', | |
| // just retry, and that's fine | |
| // However, only on Google CodeJam servers, only on the interactive problems, it | |
| // then *never* reads any data after that. | |
| } | |
| } | |
| } | |
| return function () { | |
| let c; | |
| // skip past initial whitespace | |
| while ((c = getc()) <= ' ') {} | |
| let r = [c]; | |
| do { | |
| c = getc(); | |
| if (!c || c <= ' ') { | |
| return r.join(''); | |
| } | |
| r.push(c); | |
| } while (true); | |
| }; | |
| }()); | |
| tok(); // N | |
| tok(); // A | |
| console.log('2 2'); | |
| tok(); // x // Never returns! | |
| tok(); // y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment