sqcp
sqcp copied to clipboard
Speeding up the getAllOnlinePlayers
There are a couple of things that can be done to optimize the code:
- Reduce unnecessary usage of
forEach
and using map and flat instead. It's faster to generate an array in one pass with map than to useforEach
to push into an array. - Avoid calling PopulationUtils.getTeamNameFromId() in each iteration when the
teamID
doesn't change frequently. Cache the team names in a Map where the key is theteamID
and the value is the team name. - Use a custom sorting function that leverages the fact that
playerID
is a numeric value.
Proposed revision:
getAllOnlinePlayers(state) {
const teamNameCache = new Map();
const getTeamNameFromId = (teamID) => {
if (!teamNameCache.has(teamID)) {
teamNameCache.set(teamID, PopulationUtils.getTeamNameFromId(state.population.teams, teamID));
}
return teamNameCache.get(teamID);
};
const players = state.population.teams.flatMap(team =>
team.squads.flatMap(squad =>
squad.players.map(player => ({
...player,
squad: squad.name,
team: team.name
}))
)
);
const onlinePlayers = state.population.players.onlinePlayers
.filter(player => !player.squadID || player.squadID === 'N/A')
.map(player => {
const playerCopy = {...player, squadID: undefined};
return {
...playerCopy,
squad: 'Unassigned',
team: getTeamNameFromId(playerCopy.teamID)
};
});
const allPlayers = players.concat(onlinePlayers);
allPlayers.sort((player1, player2) => player1.playerID - player2.playerID);
return allPlayers;
}
TODO: Test