Я работал над приведенной ниже функцией, которая должна сортировать набор матчей по временным интервалам и гарантировать, что команда не может играть дважды одновременно. Однако при запуске у меня возникают проблемы со списком команд, которые очищаются, а затем происходит сбой программы. Состояние компонента перед выполнением запуска выглядит следующим образом Я разместил свой код ниже и прокомментировал его, так что, надеюсь, он имеет смысл.
assignTime(){
let matches=this.state.matches;
console.log(matches);
let table = [];
let timeslots = this.state.timeLabels;
console.log(timeslots);
let pitches = this.state.pitches;
console.log(pitches);
for (let slot =0; slot<timeslots.length; slot++){ //this code block runs through every time slot
let slotMatches=[];
let slotTeams= [];
let skippedMatches =[];
for (let pitchNo = 0; pitchNo<pitches.length; pitchNo++) { //running through the available pitches
let match = matches[0];//getting first match from the list
while (slotTeams.includes(match.teamA) || slotTeams.includes(match.teamB)) { //if one of the teams is already scheduled for that slot
skippedMatches.push(match); //skip this match
let index = matches.indexOf(match);
matches.splice(index, 1); //remove that match temporarily from the list
match = matches[0]; //get the next match up
}
slotMatches.push(match); //if it passes the while loop, you can assign it to that time
let index = matches.indexOf(match);
matches.splice(index, 1); //remove the match
slotTeams.push(match.teamA, match.teamB); //put the teams into the list of teams scheduled for that time
}
matches = skippedMatches.concat(matches); //once you get past the timeslot, add the skipped matches back
table.push(slotMatches); //put the slot matches into the overall table
}
this.setState({table});
}
Я полагаю, что ошибка возникает, когда в списке больше нет совпадений, и консоль выдает эту ошибку: Ошибка типа: совпадение не определено. Я пытался найти способ закончить, когда все совпадения отсортированы, но сейчас я в растерянности.
РЕДАКТИРОВАТЬ: после изменения кода в ответе ниже, он работает, но определенные совпадения заносятся в таблицу несколько раз: