Skip to content

Commit

Permalink
Merge pull request #156 from leisim/takefirstlast
Browse files Browse the repository at this point in the history
Make sure takeFirst and takeLast doesn't crash when n > length
  • Loading branch information
passsy authored Apr 12, 2022
2 parents 1c43c45 + 4320730 commit d4eb3bd
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/src/iterable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,7 @@ extension IterableTakeFirst<E> on Iterable<E> {
/// ```
List<E> takeFirst(int n) {
final list = this is List<E> ? this as List<E> : toList();
return list.sublist(0, n);
return list.take(n).toList();
}
}

Expand All @@ -536,7 +536,7 @@ extension IterableTakeLast<E> on Iterable<E> {
/// ```
List<E> takeLast(int n) {
final list = this is List<E> ? this as List<E> : toList();
return list.sublist(length - n);
return list.reversed.take(n).reversed.toList();
}
}

Expand Down
2 changes: 2 additions & 0 deletions test/iterable_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,14 @@ void main() {
expect([].takeFirst(0), []);
expect([1, 2, 3].takeFirst(0), []);
expect([1, 2, 3].takeFirst(2), [1, 2]);
expect([1, 2, 3].takeFirst(4), [1, 2, 3]);
});

test('.takeLast()', () {
expect([].takeLast(0), []);
expect([1, 2, 3].takeLast(0), []);
expect([1, 2, 3].takeLast(2), [2, 3]);
expect([1, 2, 3].takeLast(4), [1, 2, 3]);
});

test('.firstWhile()', () {
Expand Down

0 comments on commit d4eb3bd

Please sign in to comment.