Конечно, хорошо использовать Firebase. Для этого я создал бы класс, который генерирует необходимую структуру данных и включает в себя необходимые функции для манипулирования данными.
Лига. js
class League {
constructor(matches) {
this.matches = matches;
this.table = {};
}
getStandings() {
this.matches.forEach(match => {
const { homeTeam, awayTeam } = match;
// add teams to the table
if (!this.table[homeTeam]) this.addToTable(homeTeam);
if (!this.table[awayTeam]) this.addToTable(awayTeam);
// increase the played counter
this.increasePlayed([homeTeam, awayTeam]);
// calculate won,lost, drawn
this.setResults(match);
// calculate goalsScored and goalsAgainst
this.setGoals(homeTeam, match.homeGoals, match.awayGoals);
this.setGoals(awayTeam, match.awayGoals, match.homeGoals);
});
// all is done; return the table
return this.table;
}
addToTable(team) {
this.table[team] = {
played: 0,
won: 0,
lost: 0,
drawn: 0,
goalsScored: 0,
goalsAgainst: 0
};
}
increasePlayed(teams) {
teams.forEach(team => this.table[team].played++);
}
setResults(match) {
const {
homeTeam, awayTeam, homeGoals, awayGoals
} = match;
if (homeGoals > awayGoals) {
this.table[homeTeam].won++;
this.table[awayTeam].lost++;
} else if (homeGoals < awayGoals) {
this.table[awayTeam].won++;
this.table[homeTeam].lost++;
} else {
this.table[homeTeam].drawn++;
this.table[awayTeam].drawn++;
}
}
setGoals(team, scored, against) {
this.table[team].goalsScored += scored;
this.table[team].goalsAgainst += against;
}
}
module.exports = League;
Тогда, где вам нужно Лига, создайте его экземпляр с параметром matches
, затем просто вызовите функцию getStandings()
, чтобы вычислить и вернуть таблицу.
app. js
const League = require('./League');
// note that all of the matches objects are flat
const matches = [
{
homeTeam: 'A',
awayTeam: 'B',
homeGoals: 0,
awayGoals: 3
},
{
homeTeam: 'D',
awayTeam: 'C',
homeGoals: 0,
awayGoals: 3
},
{
homeTeam: 'D',
awayTeam: 'B',
homeGoals: 0,
awayGoals: 2
},
{
homeTeam: 'A',
awayTeam: 'C',
homeGoals: 0,
awayGoals: 1
}
];
const league = new League(matches);
const standings = league.getStandings();
console.log(standings);
Сейчас выполняется app. js выведет:
{
A: {
played: 2,
won: 0,
lost: 2,
drawn: 0,
goalsScored: 0,
goalsAgainst: 4
},
B: {
played: 2,
won: 2,
lost: 0,
drawn: 0,
goalsScored: 5,
goalsAgainst: 0
},
D: {
played: 2,
won: 0,
lost: 2,
drawn: 0,
goalsScored: 0,
goalsAgainst: 5
},
C: {
played: 2,
won: 2,
lost: 0,
drawn: 0,
goalsScored: 4,
goalsAgainst: 0
}
}
Надеюсь, это поможет!