1 import Participant from './Participant';
2 import Round from './Round';
4 export const calculateScores = tournament => {
5 if (!tournament || !tournament.participants || !tournament.participants.length) return [];
6 const scores = tournament.participants.map(participant => ({ participant, score: 0 }));
7 if (!tournament.rounds || !tournament.rounds.length) return scores;
8 tournament.rounds.forEach(round => {
9 const filtered = Participant
10 .sortByResult(tournament.participants, round)
11 .map(p => ({ participant: p, result: Participant.findResult(p, round) }))
12 .filter(r => r.result && (r.result.time || r.result.forfeit))
16 let lastResult = null;
17 for (let i = 0; i < filtered.length; ++i) {
18 const score = scores.find(s => s.participant.id === filtered[i].participant.id);
20 const result = filtered[i].result;
21 const betterThanLast = lastResult === null || result.time < lastResult;
22 if (!result.forfeit && betterThanLast) {
24 lastResult = result.time;
29 if (!result.forfeit) {
30 score.score += running;
34 return scores.sort(compareScore).reverse();
37 export const compareScore = (a, b) => {
38 const a_score = a && a.score ? a.score : 0;
39 const b_score = b && b.score ? b.score : 0;
40 if (a_score < b_score) return -1;
41 if (b_score < a_score) return 1;
45 export const findParticipant = (tournament, user) => {
46 if (!tournament || !tournament.participants || !tournament.participants.length) return null;
47 if (!user || !user.id) return null;
48 return tournament.participants.find(p => p.user_id == user.id);
51 export const patchResult = (tournament, result) => {
52 if (!tournament || !tournament.rounds) return tournament;
55 rounds: tournament.rounds.map(round =>
56 round.id === result.round_id
57 ? Round.patchResult(round, result)
63 export const patchRound = (tournament, round) => {
64 if (!tournament) return tournament;
67 rounds: tournament.rounds.map(r => r.id === round.id ? { ...r, ...round } : r),
71 export const sortParticipants = tournament => {
72 if (!tournament || !tournament.participants || !tournament.participants.length) {
77 participants: tournament.participants.sort(Participant.compareUsername),