Created
August 13, 2017 16:41
-
-
Save ericabell/55bb80726e41313914e7aad800c3d6ec to your computer and use it in GitHub Desktop.
Read a series of numbers from the terminal, compute their sum when input stream closes
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
const readline = require('readline'); | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout, | |
prompt: 'Enter numbers sep by newlines. Ctrl-d when done> \n' | |
}); | |
let inputStack = []; | |
// display our prompt with instructions for the user | |
rl.prompt(); | |
// every time user hits enter, the 'line' event fires | |
rl.on('line', (input) => { | |
// add their input to our stack | |
inputStack.push(Number(input)); | |
}).on('close', () => { // ctrl-d closes the stream, add the numbers, clean up | |
console.log('The sum is: ' + inputStack.reduce( (sum,val) => { | |
return sum +val; | |
}, 0)); | |
process.exit(0); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment