To modify the function so that it returns only the questions that have an updated position, we need to compare the original positions of the questions with their new positions after reordering. If a question's position has changed, it should be included in the resulting map. Otherwise, the map should be empty if no positions have changed.
Here’s the modified code:
fun reorder(
question: QuestionId,
position: Int,
): Map<QuestionId, Int> {
val currentIndex = questions.indexOfFirst { it.id == question }
if (currentIndex == -1) return emptyMap()
val originalPositions = questions.mapIndexed { index, q -> q.id to (index + 1) }.toMap()
val newIndex = if (currentIndex < position) position - 1 else position
val reorderedQuestions = questions
.toMutableList()
.apply { add(newIndex, removeAt(currentIndex)) }
val newPositions = reorderedQuestions
.mapIndexed { index, q -> q.id to (index + 1) }
.toMap()
// Find questions whose positions have changed
val updatedPositions = newPositions
.filter { (id, newPos) -> originalPositions[id] != newPos }
.toMap()
return updatedPositions
}
Explanation:
- Original Positions: We first create a map (
originalPositions) that stores the current positions of all questions.
- Reordering: We then reorder the questions as before, placing the specified question at the new position.
- New Positions: After reordering, we create another map (
newPositions) that stores the new positions of all questions.
- Filtering Updated Positions: We filter the
newPositions map to include only those questions whose positions have changed compared to originalPositions.
- Return Result: The function returns a map containing only the questions with updated positions. If no positions have changed, the map will be empty.
This ensures that the function returns only the questions that have been repositioned, as required.