class Queue { constructor() { this.players = fetchPlayers(); } removePlayers(playersToRemove) { playersToRemove.forEach(player => { const index = this.players.indexOf(player); this.players.splice(index, 1); }) } getRandomPlayer() { return this.players[Math.floor(Math.random() * this.players.length)]; } calculateLessThanPercentage(player) { return 5 / 100 * player.mmr + player.mmr } calculateGreaterThanPercentage(player) { return player.mmr - 5 / 100 * player.mmr } searching() { const firstPlayer = this.getRandomPlayer(); const secondPlayer = this.players.find( playerTwo => playerTwo.mmr < this.calculateLessThanPercentage(firstPlayer) && playerTwo.mmr > this.calculateGreaterThanPercentage(firstPlayer) && playerTwo.id != firstPlayer.id ); if (!secondPlayer) { return null; } const matchedPlayers = [firstPlayer, secondPlayer]; this.removePlayers(matchedPlayers); return matchedPlayers; } } const ActiveQueue = new Queue(); const getPlayersButton = document.getElementById("getPlayers"); const playersResults = document.getElementById("players"); const allPlayers = document.getElementById("allPlayers"); getPlayersButton.addEventListener("click", () => { getPlayers(ActiveQueue, playersResults, allPlayers) }); // getPlayersButton click event handler function getPlayers(queue, resultsElement, allPlayersElement) { const searchResults = queue.searching(); resultsElement.innerHTML = JSON.stringify(searchResults, null, 2); allPlayersElement.innerHTML = "Remaining Players: " + JSON.stringify(queue.players, null, 2); } // to get data function fetchPlayers() { return [ { name: "Player One", id: 1, mmr: 500 }, { name: "Player Two", id: 2, mmr: 800 }, { name: "Player Three", id: 3, mmr: 810 }, { name: "Player Four", id: 4, mmr: 815 }, { name: "Player Five", id: 5, mmr: 510 }, { name: "Player Six", id: 6, mmr: 540 }, { name: "Player Seven", id: 7, mmr: 530 }, { name: "Player Eight", id: 8, mmr: 520 } ]; }
button { margin-top: 10px; }
Click to get players (scroll all the way down to see remaining players) <br /> <button id="getPlayers">Get Players</button> <pre id="players"></pre> <br /> <hr /> <pre id="allPlayers"></pre>