-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path2-read_file.js
More file actions
42 lines (37 loc) · 1.43 KB
/
Copy path2-read_file.js
File metadata and controls
42 lines (37 loc) · 1.43 KB
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
const fs = require('fs');
const countStudents = (dataPath) => {
if (!fs.existsSync(dataPath)) {
throw new Error('Cannot load the database');
}
if (!fs.statSync(dataPath).isFile()) {
throw new Error('Cannot load the database');
}
const fileLines = fs
.readFileSync(dataPath, 'utf-8')
.toString('utf-8')
.trim()
.split('\n');
const studentGroups = {};
const dbFieldNames = fileLines[0].split(',');
const studentPropNames = dbFieldNames.slice(0, dbFieldNames.length - 1);
for (const line of fileLines.slice(1)) {
const studentRecord = line.split(',');
const studentPropValues = studentRecord.slice(0, studentRecord.length - 1);
const field = studentRecord[studentRecord.length - 1];
if (!Object.keys(studentGroups).includes(field)) {
studentGroups[field] = [];
}
const studentEntries = studentPropNames
.map((propName, idx) => [propName, studentPropValues[idx]]);
studentGroups[field].push(Object.fromEntries(studentEntries));
}
const totalStudents = Object
.values(studentGroups)
.reduce((pre, cur) => (pre || []).length + cur.length);
console.log(`Number of students: ${totalStudents}`);
for (const [field, group] of Object.entries(studentGroups)) {
const studentNames = group.map((student) => student.firstname).join(', ');
console.log(`Number of students in ${field}: ${group.length}. List: ${studentNames}`);
}
};
module.exports = countStudents;