Skip to content

Commit

Permalink
#41: Added replace where
Browse files Browse the repository at this point in the history
  • Loading branch information
vanlooverenkoen committed Apr 17, 2021
1 parent 2d8d679 commit 8a62869
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/src/extension/list_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ extension ListExtensions<T> on List<T> {
insert(index, newData);
}

///Replaces all items that matches where with [newData]
void replaceWhere(bool Function(T) where, T newData) {
final whereResult = this.where(where);
print(whereResult);
whereResult.forEach((result) {
if (result == null) return;
final index = indexOf(result);
removeAt(index);
insert(index, newData);
});
}

/// Sorts the list based on the comparable returned by [by]. By default
/// the sorting is [ascending]
void sortBy<R>(Comparable<R>? by(T item), {bool ascending = true}) {
Expand Down
9 changes: 9 additions & 0 deletions test/extension/list_extension_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ void main() {
expect(sut..replaceFirstWhere((item) => item == 2, 100),
[1, 100, 3, 4, 5, 6, 7, 8, 9, 10]);
});
test('Test replaceWhere', () {
expect(sut, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
expect(
sut
..replaceWhere(
(item) => item == 2 || item == 4 || item == 1 || item == 9,
100),
[100, 100, 3, 100, 5, 6, 7, 8, 100, 10]);
});
test('Test sort by', () {
sut.sortBy((e) => 10 - e);
expect(sut, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
Expand Down

0 comments on commit 8a62869

Please sign in to comment.