diff --git a/CHANGELOG.md b/CHANGELOG.md index d90c157..4255c05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/lib/src/iterable_extensions.dart b/lib/src/iterable_extensions.dart index 1bf4b3e..96e775b 100644 --- a/lib/src/iterable_extensions.dart +++ b/lib/src/iterable_extensions.dart @@ -56,6 +56,27 @@ extension IterableExtension on Iterable { 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 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 whereNot(bool Function(T element) test) => where((element) => !test(element)); diff --git a/test/extensions_test.dart b/test/extensions_test.dart index 3b1401a..ea9515d 100644 --- a/test/extensions_test.dart +++ b/test/extensions_test.dart @@ -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([1, '2', 3]).separated(0), [1, 0, '2', 0, 3]); + expect(iterable(['a', 'b']).separated(0), ['a', 0, 'b']); + }); + }); group('none', () { test('empty', () { expect(iterable([]).none(unreachable), true);