Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speeding up the getAllOnlinePlayers #12

Open
milutinke opened this issue May 26, 2023 · 0 comments
Open

Speeding up the getAllOnlinePlayers #12

milutinke opened this issue May 26, 2023 · 0 comments

Comments

@milutinke
Copy link
Owner

There are a couple of things that can be done to optimize the code:

  1. 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 use forEach to push into an array.
  2. 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 the teamID and the value is the team name.
  3. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant