I have the following code that shuffles player records of string,object to Record<string(Team name),Record<string,object>(Player's)> but every team need's to have a captain.
var randomProperty = function (obj, amount) {
var keys = Object.keys(obj);
const newObj = [];
for (let index = 0; index < amount; index++) {
const item = keys[(keys.length * Math.random()) << 0];
newObj.push(obj[item]);
delete obj[item];
}
return newObj;
};
function shuffle(teamSize) {
let teams = {
unknown: {
["1"]: {
role: "test",
captain: false
},
["2"]: {
role: "test",
captain: false
},
["3"]: {
role: "test",
captain: false
},
["4"]: {
role: "test",
captain: false
}
}
};
const playersClone = Array.from(Object.entries(teams.unknown));
const teamCount = Math.floor(playersClone.length / teamSize);
const clone = Array.from(playersClone).slice(0, teamCount * teamSize);
const captains =
clone.filter((x) => x[1].captain).length == 0
? randomProperty(clone, teamCount)
: clone.filter((x) => x[1].captain);
for (let i = 0; i < playersClone.length; i++) {
const captains = clone;
const player = clone.splice(Math.random() * clone.length, 1)[0];
teams = {
...teams,
[i % teamCount]: {
...teams[i % teamCount],
[player[0]]: {
role: player[1].role,
captain: player[1].captain
}
}
};
}
return teams;
}
console.log(shuffle(2));
What I want to achieve is that before the teams are shuffled they need to have a captain on each team.