Skip to content

Commit

Permalink
Add Multiset.combine.
Browse files Browse the repository at this point in the history
  • Loading branch information
renggli committed Dec 2, 2023
1 parent 615d824 commit 4083a31
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/src/collection/multiset.dart
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,21 @@ class Multiset<E> extends IterableBase<E> {
}
}

/// Returns a new [Multiset] by evaluating [callback] element-wise for each
/// distinct element of `this` and [other].
Multiset<E> combine(
Iterable<E> other, int Function(E element, int a, int b) callback) {
if (other is Multiset<E>) {
final result = Multiset<E>();
for (final element in {...distinct, ...other.distinct}) {
result.add(element, callback(element, this[element], other[element]));
}
return result;
} else {
return combine(Multiset.of(other), callback);
}
}

/// Returns a new [Multiset] with the elements that are in the receiver as
/// well as those in [other].
Multiset<E> intersection(Iterable<Object?> other) {
Expand Down
22 changes: 22 additions & 0 deletions test/collection_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3140,6 +3140,28 @@ void main() {
expect(firstSet.containsAll([1, 2]), isFalse);
expect(firstSet.containsAll(['a', null]), isFalse);
});
test('combine', () {
expect(firstSet.combine(secondSet, (element, a, b) => a + b),
unorderedEquals(['a', 'a', 'b', 'c', 'c', 'c', 'd', 'd']));
expect(firstSet.combine(secondSet, (element, a, b) => min(a, b)),
unorderedEquals(['a', 'c']));
expect(firstSet.combine(secondSet, (element, a, b) => max(0, a - b)),
unorderedEquals(['b', 'c']));
expect(
firstSet.combine(secondSet, (element, a, b) => max(a - b, b - a)),
unorderedEquals(['b', 'c', 'd', 'd']));
});
test('combine (iterable)', () {
expect(firstSet.combine(secondList, (element, a, b) => a + b),
unorderedEquals(['a', 'a', 'b', 'c', 'c', 'c', 'd', 'd']));
expect(firstSet.combine(secondList, (element, a, b) => min(a, b)),
unorderedEquals(['a', 'c']));
expect(firstSet.combine(secondList, (element, a, b) => max(0, a - b)),
unorderedEquals(['b', 'c']));
expect(
firstSet.combine(secondList, (element, a, b) => max(a - b, b - a)),
unorderedEquals(['b', 'c', 'd', 'd']));
});
test('intersection', () {
expect(firstSet.intersection(secondSet), unorderedEquals(['a', 'c']));
expect(firstSet.intersection(secondSet).distinct,
Expand Down

0 comments on commit 4083a31

Please sign in to comment.