JSFiddle - React, Tailwind, and code Playground
by cmruser
JavaScript
function getNumberOfTeams() {
while (true) {
let numTeams = parseInt(prompt("enter number of teams"));
if (numTeams >= 2) {
return numTeams;
}
}
}
function getTeamNames(numTeams) {
const teamNames = [];
for (let i = 0; i < numTeams; i++) {
while (true) {
const teamName = prompt("enter team names: " + (i + 1));
const numWords = teamName.split(" ").length;
if (numWords > 2) {
console.log("require at most 2 words");
} else if (teamName.length < 2) {
console.log("require at least 2 characters");
} else {
teamNames.push(teamName);
break;
}
}
}
return teamNames;
}
function getNumberOfGamesPlayed(numTeams) {
while (true) {
const gamesPlayed = parseInt(prompt("enter game played"));
if (gamesPlayed >= numTeams - 1) {
return gamesPlayed;
}
console.log("invalid number of games");
}
}
function getTeamWins(teamNames, gamesPlayed) {
const teamWins = [];
for (let i = 0; i < teamNames.length; i++) {
const team = teamNames[i];
while (true) {
const wins = parseInt(prompt(`Enter the number of wins for ${team}`));
if (wins > gamesPlayed) {
console.log("Try again");
} else if (wins < 0) {
console.log("Minimum number of wins is 0");
} else {
teamWins.push([team, wins]);
break;
}
}
}
return teamWins;
}
function getSecondItem(item) {
return item[1];
}
const numTeams = getNumberOfTeams();
const teamNames = getTeamNames(numTeams);
const gamesPlayed = getNumberOfGamesPlayed(numTeams);
const teamWins = getTeamWins(teamNames, gamesPlayed);
const sortedTeam = teamWins.sort((a, b) => getSecondItem(a) - getSecondItem(b));
let gamePairings = [];
let gamesToMake = sortedTeam.length;
for (let gameNum = 0; gameNum < gamesToMake; gameNum++) {
let homeTeam = sortedTeam[gameNum][0];
let awayTeam = sortedTeam[numTeams - 1 - gameNum][0];
gamePairings.push([homeTeam,...