unique<T> function
Eliminates all except the first element from every consecutive group of equivalent
elements from the list and returns the new logical length of the collection.
If the collection is growable, it will automatically shrink to the new size. If the collection is fixed-length, the elements past the returned index are left in an unspecified state.
Example:
final list = [1, 1, 2, 2, 3, 2, 1];
final newLength = unique(list); // list becomes [1, 2, 3, 2, 1], returns 5
Implementation
int unique<T>(List<T> list, {bool Function(T, T)? equals}) {
if (list.isEmpty) return 0;
equals ??= (a, b) => a == b;
int writeIndex = 1;
for (int readIndex = 1; readIndex < list.length; readIndex++) {
if (!equals(list[writeIndex - 1], list[readIndex])) {
list[writeIndex] = list[readIndex];
writeIndex++;
}
}
if (list.length > writeIndex) {
try {
list.length = writeIndex;
} catch (_) {
// Ignored if list is fixed-length, user will need to rely on the returned index.
}
}
return writeIndex;
}