Skip to content
This repository has been archived by the owner on Oct 22, 2024. It is now read-only.

Commit

Permalink
Add ListExtensions.firstOrNull, lastOrNull, singleOrNull.
Browse files Browse the repository at this point in the history
  • Loading branch information
scheglov committed Sep 6, 2023
1 parent 91afde4 commit 8c2f430
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

- Adds `shuffled` to `IterableExtension`.
- Shuffle `IterableExtension.sample` results.
* Add `List.firstOrNull`, `List.lastOrNull`, and `List.singleOrNull` extension methods.
They repeat corresponding methods for `Iterable`, but avoid creating iterator objects.

## 1.18.0

Expand Down
19 changes: 19 additions & 0 deletions lib/src/list_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,25 @@ extension ListExtensions<E> on List<E> {
yield slice(i, min(i + length, this.length));
}
}

/// The first element, or `null` if the list is empty.
E? get firstOrNull {
return isNotEmpty ? this[0] : null;
}

/// The last element, or `null` if the list is empty.
E? get lastOrNull {
final length = this.length;
return length != 0 ? this[length - 1] : null;
}

/// The single element of the list, or `null`.
///
/// The value is `null` if the list is empty
/// or it contains more than one element.
E? get singleOrNull {
return length == 1 ? this[0] : null;
}
}

/// Various extensions on lists of comparable elements.
Expand Down
33 changes: 33 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1864,6 +1864,39 @@ void main() {
expect(() => [1].slices(0), throwsRangeError);
});
});
group('.firstOrNull', () {
test('empty', () {
expect(<int>[].firstOrNull, null);
});
test('single', () {
expect([1].firstOrNull, 1);
});
test('first of multiple', () {
expect([1, 3, 5].firstOrNull, 1);
});
});
group('.lastOrNull', () {
test('empty', () {
expect(<int>[].lastOrNull, null);
});
test('single', () {
expect([1].lastOrNull, 1);
});
test('last of multiple', () {
expect([1, 3, 5].lastOrNull, 5);
});
});
group('.singleOrNull', () {
test('empty', () {
expect(<int>[].singleOrNull, null);
});
test('single', () {
expect([1].singleOrNull, 1);
});
test('multiple', () {
expect([1, 3, 5].singleOrNull, null);
});
});
});
group('on comparable', () {
group('.binarySearch', () {
Expand Down

0 comments on commit 8c2f430

Please sign in to comment.