HackerRank Inheritance | JS Solution
Problem
HackerRank detailed problem description can be found here.
Sample Input
Robot Bobert 5135617
2
100 80
Sample Output
Name: Bobert, Robot
ID: 5135617
Grade: O
JavaScript Solution
class Student extends Person {
/*
* Class Constructor
*
* @param firstName - A string denoting the Person's first name.
* @param lastName - A string denoting the Person's last name.
* @param id - An integer denoting the Person's ID number.
* @param scores - An array of integers denoting the Person's test scores.
*/
constructor(firstName, lastName, idNumber, scores) {
super(firstName, lastName, idNumber);
this.scores = scores;
}
/*
* Method Name: calculate
* @return A character denoting the grade.
*/
// Solution #1
calculate() {
const averageScore = this.scores.reduce((a, b) => a + b) / this.scores.length;
if (averageScore >= 90 && averageScore <= 100) {
return 'O';
} else if (averageScore >= 80 && averageScore < 90) {
return 'E';
} else if (averageScore >= 70 && averageScore < 80) {
return 'A';
} else if (averageScore >= 55 && averageScore < 70) {
return 'P';
} else if (averageScore >= 40 && averageScore < 55) {
return 'D';
} else {
return 'T';
}
}
// Solution #2
calculate() {
const averageScore = this.scores.reduce((a, b) => a + b) / this.scores.length;
switch (true) {
case (averageScore >= 90 && averageScore <= 100):
return 'O';
case (averageScore >= 80 && averageScore < 90):
return 'E';
case (averageScore >= 70 && averageScore < 80):
return 'A';
case (averageScore >= 55 && averageScore < 70):
return 'P';
case (averageScore >= 40 && averageScore < 55):
return 'D';
default:
return 'T';
}
}
}
Resources
- Inheritance algorithm by HackerRank
- Classes and switch by MDN Web Docs