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

Commit

Permalink
separated method added in Iterable extension
Browse files Browse the repository at this point in the history
  • Loading branch information
kishan-dhankecha committed May 20, 2024
1 parent 4718398 commit d17150c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 1.19.0-wip

- Adds `shuffled` to `IterableExtension`.
- Adds `separated` to `IterableExtension`.
- Shuffle `IterableExtension.sample` results.
- Fix `mergeSort` when the runtime iterable generic is a subtype of the static
generic.
Expand Down
21 changes: 21 additions & 0 deletions lib/src/iterable_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,27 @@ extension IterableExtension<T> on Iterable<T> {
return chosen;
}

/// Separates the elements of the iterable with the specified separator.
///
/// The [separated] method takes a separator as input and returns a new
/// iterable where the elements are separated by the specified separator.
///
/// Example:
/// ```dart
/// final list = [1, 2, 3, 4];
/// final separatedList = list.separated(0);
/// print(separatedList); // Output: [1, 0, 2, 0, 3, 0, 4]
/// ```
Iterable<T> separated(T separator) sync* {
final iterator = this.iterator;
if (!iterator.moveNext()) return;
yield iterator.current;
while (iterator.moveNext()) {
yield separator;
yield iterator.current;
}
}

/// The elements that do not satisfy [test].
Iterable<T> whereNot(bool Function(T element) test) =>
where((element) => !test(element));
Expand Down
19 changes: 19 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -850,6 +850,25 @@ void main() {
]);
});
});
group('.separated', () {
test('empty', () {
expect(iterable([]).separated(unreachable), isEmpty);
});

test('single', () {
expect(iterable([1]).separated(0), [1]);
});

test('multiple', () {
expect(iterable([1, 2, 3]).separated(0), [1, 0, 2, 0, 3]);
expect(iterable(['a', 'b']).separated('-'), ['a', '-', 'b']);
});

test('dynamic', () {
expect(iterable<Object>([1, '2', 3]).separated(0), [1, 0, '2', 0, 3]);
expect(iterable<Object>(['a', 'b']).separated(0), ['a', 0, 'b']);
});
});
group('none', () {
test('empty', () {
expect(iterable([]).none(unreachable), true);
Expand Down

0 comments on commit d17150c

Please sign in to comment.