Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Iterable.intersperse extension method #309

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## 1.19.0-wip

- Adds `shuffled` to `IterableExtension`.
- Add `Iterable.shuffled` and `Iterable.intersperse` extension methods.
- Shuffle `IterableExtension.sample` results.

## 1.18.0
Expand Down
15 changes: 15 additions & 0 deletions lib/src/iterable_extensions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,21 @@ extension IterableExtension<T> on Iterable<T> {
yield slice;
}
}

/// Insert a specific element between each two elements of this iterator.
///
/// For example, `[1, 2, 3].intersperse(0)` returns `(1, 0, 2, 0, 3)`.
Iterable<T> intersperse(T element) sync* {
var first = true;
for (var e in this) {
if (first) {
first = false;
} else {
yield element;
}
yield e;
}
}
}

/// Extensions that apply to iterables with a nullable element type.
Expand Down
17 changes: 17 additions & 0 deletions test/extensions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1262,6 +1262,23 @@ void main() {
expect(l3.toList(), [4, 5]);
});
});
group('.intersperse', () {
test('empty', () {
expect(iterable(<int>[]).intersperse(0), []);
});
test('one element', () {
expect(iterable(<int>[1]).intersperse(0), [1]);
});
test('two elements', () {
expect(iterable(<int>[1, 2]).intersperse(0), [1, 0, 2]);
});
test('more elements', () {
expect(
iterable(<int>[1, 2, 3, 4]).intersperse(0),
[1, 0, 2, 0, 3, 0, 4],
);
});
});
});

group('Comparator', () {
Expand Down