当然可以使用 Firebase。为此,我将创建一个类来生成所需的数据结构并在其中包含操作数据所需的函数。
League.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;
然后在你需要 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
}
}
希望这会有所帮助!