In: Computer Science
Using a text editor or IDE, copy the following list of names and
grade scores and save it as a text file named scores.txt:
Name, Score
Joe Besser,70
Curly Joe DeRita,0
Larry Fine,80
Curly Howard,65
Moe Howard,100
Shemp Howard,85
Create a JavaScript program of the files that display high, low,
and average scores based on input from scores.txt. Verify that the
file exists and then use string functions/methods to parse the file
content and add each score to an array. Display the array contents
and then calculate and display the high, low, and average score.
Format the average to two decimal places. Note that the program
must work for any given number of scores in the file. Do not assume
there will always be six scores and use Node Js as IDE.
If you have any problem with the code feel free to comment.
Program
const fs = require('fs');
//for storing student details
let studentDetails = {};
fs.readFile('scores.txt', 'utf-8', (err, data) => {
//split data in by new line
const rawDetails = data.split(/\r?\n/);
for (let i = 0; i < rawDetails.length; i++) {
//splitting the data by comma
let ar = rawDetails[i].split(',');
studentDetails[i] = { name: ar[0], score: parseInt(ar[1]) };
}
let sum = 0;
let high = studentDetails[0].score;
let low = studentDetails[0].score;
for (let i = 0; i < rawDetails.length; i++) {
//calculating sum
sum += studentDetails[i].score;
//finding high score
if (high < studentDetails[i].score) high = studentDetails[i].score;
//finding low score
if (low > studentDetails[i].score) low = studentDetails[i].score;
}
//calculating avg
const avg = sum / rawDetails.length;
//printing the result
console.log(`High score: ${high}`);
console.log(`Low score: ${low}`);
console.log(`Average score: ${avg.toFixed(2)}`);
});
Output
