Last active
September 23, 2016 08:23
-
-
Save sujoyu/393fafacea414711aecbcd682d102774 to your computer and use it in GitHub Desktop.
javascript sequential stdin reader.
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 reader = new Reader(10); | |
var input = {}; | |
reader.read(function(line) { | |
var vars = line.split(' ') | |
input.m = parseInt(vars[0]); | |
input.n = parseInt(vars[1]); | |
}).then(reader.read(function(line) { | |
input.o = line; | |
})).then(function() { | |
input.xs = []; | |
var promise = Promise.resolve(); | |
for (var i = 0; i < input.m; i++) { | |
promise = promise.then(reader.read(function(line) { | |
input.xs.push(line); | |
})); | |
} | |
return promise; | |
}).then(function() { | |
reader.close(); | |
console.log('input: '); | |
console.log(input); // main process | |
}).catch(function(e) { | |
console.error(e); | |
}); | |
function Reader(maxLines) { | |
var lines = []; | |
for (var i = 0; i < maxLines; i++) { | |
var line = { | |
resolve: null, | |
setLine: function(line) { this.resolve(line); } | |
} | |
line.promise = new Promise(function(resolve) { | |
line.resolve = resolve; | |
}) | |
lines.push(line); | |
} | |
var reader = require('readline').createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
var initr = 0 | |
reader.on('line', function (line) { | |
lines[initr].setLine(line); | |
initr++; | |
}); | |
var itr = 0 | |
this.read = function(func) { | |
line = lines[itr]; | |
itr++; | |
return line.promise.then(func) | |
} | |
this.close = function() { | |
reader.close(); | |
} | |
} |
Author
sujoyu
commented
Sep 23, 2016
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment