tails<T> function

List<T> tails<T>(
  1. List<T> lists,
  2. int n
)

Get the last n elements from lists.

var paths = ['Downloads', 'ft', 'README.md'];
print(tail(paths, 0)); // []; empty list
print(tail(paths, 1)); // ['README.md']
print(tail(paths, 2)); // ['ft', 'README.md']
print(tail(paths, 3)); // ['Downloads', 'ft', 'README.md']
print(tail(paths, 4)); // ['Downloads', 'ft', 'README.md']

Implementation

List<T> tails<T>(List<T> lists, int n) {
  if (n < 0) throw ArgumentError('tail n must be non-negative');
  if (n == 0) return [];
  if (lists.isEmpty) return [];

  // Using max(0, ...) ensures that sublist start index is not negative
  // in case n is larger than lists.length, effectively returning the whole list.
  return lists.sublist(max(0, lists.length - n));
}