maxLength method
If the list has more than maxLength elements, remove the last elements so it remains with only maxLength elements. If the list has maxLength or less elements, doesn't change anything.
If you want, you can provide a priority
comparator, such as the elements to be removed are
the ones that would be in the end of a list sorted with this comparator (the order of the
remaining elements won't change).
Implementation
IList<T> maxLength(
int maxLength, {
int Function(T a, T b)? priority,
}) {
var originalLength = length;
if (originalLength <= maxLength)
return this;
else if (priority == null)
return IList._unsafe(_l.maxLength(maxLength), config: config);
else {
List<T> toBeRemovedFromEnd = unlock..sort(priority);
toBeRemovedFromEnd = toBeRemovedFromEnd.sublist(maxLength);
var result = <T>[];
for (int i = originalLength - 1; i >= 0; i--) {
var item = this[i];
if (!toBeRemovedFromEnd.contains(item))
result.add(item);
else
toBeRemovedFromEnd.remove(item);
}
return IList(result.reversed);
}
}