findFirstDuplicateByIndex<T> function
Returns the first duplicate element found in the list based on the earliest second occurrence (lowest second index). Uses deep equality for complex objects. Throws ArgumentError if no duplicates found.
Implementation
T findFirstDuplicateByIndex<T>(final List<T> list) {
const DeepCollectionEquality equality = DeepCollectionEquality();
final Map<int, T> duplicateCandidates = <int, T>{};
final List<T> seen = <T>[];
// Map from element to first index it appeared
final Map<T, int> firstIndexes = <T, int>{};
for (int i = 0; i < list.length; i++) {
final T element = list[i];
// Check if element seen before (by deep equality)
final int seenIndex = seen.indexWhere(
(final T e) => equality.equals(e, element),
);
if (seenIndex == -1) {
seen.add(element);
firstIndexes[element] = i;
} else {
// Duplicate found; record the second occurrence index as key
duplicateCandidates[i] = element;
}
}
if (duplicateCandidates.isEmpty) {
throw ArgumentError('No duplicates found');
}
// Find the duplicate with the smallest second occurrence index
final int minSecondIndex = duplicateCandidates.keys.reduce(
(final int a, final int b) => a < b ? a : b,
);
return duplicateCandidates[minSecondIndex] as T;
}