dropRight<T> function

List<T> dropRight<T>(
  1. List<T> list, [
  2. int n = 1
])

removes n number of elements from the ending of list

//If used as method, it directly alter the list's object
var list = <int>[1, 2, 3, 4, 5];
list.dropRight(); // list = [1, 2, 3, 4];

list.dropRight(3); // list = [1];

list.dropRight(5); // list = []; // does not throw error :D

//If used as function,
//it creates a new copy of the output and list's object is untouched

var list = <int>[1, 2, 3, 4, 5];
var newObject = dropRight(list); // newObject = [1, 2, 3, 4];

var newObject = dropRight(list, 3); // newObject = [1, 2];

var newObject = dropRight(list, 5); // newObject = []; // does not throw error :D

Implementation

List<T> dropRight<T>(List<T> list, [int n = 1]) {
  if (n > 0 && list.isNotEmpty) {
    var result = <T>[];
    for (var i = 0; i < list.length - n; i++) {
      result.add(list[i]);
    }
    return result;
  }
  return <T>[];
}