maxLength method

  1. @useResult
IList<T> maxLength(
  1. int maxLength, {
  2. int priority(
    1. T a,
    2. T b
    )?,
})

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

@useResult
IList<T> maxLength(
  int maxLength, {
  int Function(T a, T b)? priority,
}) {
  final 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);
    final result = <T>[];
    for (int i = originalLength - 1; i >= 0; i--) {
      final item = this[i];
      if (!toBeRemovedFromEnd.contains(item))
        result.add(item);
      else
        toBeRemovedFromEnd.remove(item);
    }
    return IList(result.reversed);
  }
}