I am currently enrolled in a Udemy JavaScript Course where I am going through all the coding exercises again using ES6.
Within my array of teams, each team is represented as an object. My goal is to compare these teams and determine the winner, while also ensuring that this functionality can easily adapt to adding more teams in the future.
The code snippet below showcases my progress thus far. I am looking to make it capable of evaluating any number of arrays, however, at the moment it only assesses the first two arrays.
class Team {
constructor(teamName, scores) {
this.teamName = teamName,
this.scores = scores;
this.avgScore = Math.floor(this.scores.reduce((prev, cur) => (prev + cur) / this.scores.length));
}
}
// Generating random scores
randomNumber = () => parseInt(Math.random() * 250);
randomScore = () => [randomNumber(), randomNumber(), randomNumber()];
// Creating the teams
let teams = [
new Team('Team John', randomScore()),
new Team('Team Mike', randomScore()),
new Team('Team Mary', randomScore())
]
// for debugging purposes
for (el of teams) {
console.log(`${el.teamName}: ${el.avgScore}`)
}
// attempting to make this scalable
let winner = 0;
calcWinner = () => teams.reduce((prev, cur, index) => cur.avgScore > prev.avgScore ? winner = index : winner = winner);
calcWinner();
// More debugging
console.log(winner);
// Logging result to the console
console.log(`The team with the highest average is ${teams[winner].teamName}, with a score of ${teams[winner].avgScore}`)