forked from ga-wdi-boston/node-api-promises-diagnostic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiagnostic.js
52 lines (47 loc) · 1.39 KB
/
diagnostic.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Write a function to sum the numbers in a file.
//
// This function should take the name of a plain text file with one number per
// line, as in data/integers.txt.
// It should return a Promise resolved with the sum of the numbers.
//
// Blank lines should be ignored.
// However, if there is a line with non-numeric content (e.g. "oops"),
// the Promise returned should be rejected.
//
'use strict';
const fs = require('fs');
// change this function to return a Promise
// resolved or rejected as appropriate
// use the following as the new function signature
// const sumLines = (filename) => {
const sumLines = (filename, callback) => {
fs.readFile(filename, { encoding: 'utf8' }, (err, lines) => {
let lno = 0;
let sum = lines.split('\n').reduce((prev, curr, i) => {
lno = i;
return prev + (+curr);
}, 0);
let error = isNaN(sum) && new Error(`line ${lno}: not a number`);
callback(error, sum);
});
};
const sumLinesOfArbitraryLengthFile = (filename, callback) => {
const rl = require('readline');
const rli = rl.createInterface({
input: fs.createReadStream(filename),
});
let lno = 0;
let sum = 0;
rli.on('line', (line) => {
lno++;
sum += +line;
});
rli.on('close', () => {
let error = isNaN(sum) && new Error(`line ${lno}: not a number`);
callback(error, sum);
});
};
module.exports = {
sumLines,
sumLinesOfArbitraryLengthFile,
};