Created
February 9, 2023 05:38
-
-
Save E-fais/e996d9875ddc49938453dcb9028bb261 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react'; | |
function CreateTeams({ players }) { | |
// Calculate the ideal size for each team | |
const teamSize = Math.ceil(players.length / 2); | |
// Filter players into different skill categories | |
let goodPlayers = players.filter(player => player.skill === "good"); | |
let averagePlayers = players.filter(player => player.skill === "average"); | |
let bestPlayers = players.filter(player => player.skill === "best"); | |
// Initialize state for each team | |
const [team1, setTeam1] = useState([]); | |
const [team2, setTeam2] = useState([]); | |
// Loop through the ideal team size | |
for (let i = 0; i < teamSize; i++) { | |
// If there are still "good" players, add one to team1 | |
if (goodPlayers.length > 0) { | |
setTeam1(prevTeam1 => [...prevTeam1, goodPlayers.pop()]); | |
} | |
// If there are still "good" players and team2 isn't full, add one to team2 | |
if (goodPlayers.length > 0 && team2.length < teamSize) { | |
setTeam2(prevTeam2 => [...prevTeam2, goodPlayers.pop()]); | |
} | |
// If there are still "average" players, add one to team1 | |
if (averagePlayers.length > 0) { | |
setTeam1(prevTeam1 => [...prevTeam1, averagePlayers.pop()]); | |
} | |
// If there are still "average" players and team2 isn't full, add one to team2 | |
if (averagePlayers.length > 0 && team2.length < teamSize) { | |
setTeam2(prevTeam2 => [...prevTeam2, averagePlayers.pop()]); | |
} | |
// If there are still "best" players, add one to team1 | |
if (bestPlayers.length > 0) { | |
setTeam1(prevTeam1 => [...prevTeam1, bestPlayers.pop()]); | |
} | |
// If there are still "best" players and team2 isn't full, add one to team2 | |
if (bestPlayers.length > 0 && team2.length < teamSize) { | |
setTeam2(prevTeam2 => [...prevTeam2, bestPlayers.pop()]); | |
} | |
} | |
// Render the two teams | |
return ( | |
<> | |
<h2>Team 1</h2> | |
<ul> | |
{team1.map(player => ( | |
<li key={player.id}>{player.name}</li> | |
))} | |
</ul> | |
<h2>Team 2</h2> | |
<ul> | |
{team2.map(player => ( | |
<li key={player.id}>{player.name}</li> | |
))} | |
</ul> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment