Skip to content

Commit 8f9ebc9

Browse files
authored
Implement disjoint method for traversable (#86)
1 parent 132a27b commit 8f9ebc9

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/Collection/Traversable.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,27 @@ public function filterNot(callable $predicate)
117117
});
118118
}
119119

120+
/**
121+
* Returns true if the two specified collections have no elements in common.
122+
*
123+
* @param Traversable<T> $traversable
124+
*/
125+
public function disjoint(self $traversable): bool
126+
{
127+
if ($this->isEmpty() || $traversable->isEmpty()) {
128+
return true;
129+
}
130+
131+
$iterator = $traversable->getIterator();
132+
while ($iterator->hasNext()) {
133+
if ($this->contains($iterator->next())) {
134+
return false;
135+
}
136+
}
137+
138+
return true;
139+
}
140+
120141
/**
121142
* @return T
122143
*/

tests/Collection/SetTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,4 +264,15 @@ public function testSetRemoveAll(): void
264264
self::assertTrue(Set::ofAll(['alpha', 'beta', 'gamma'])->removeAll(Set::ofAll(['1', '2', '3']))->equals(Set::ofAll(['alpha', 'beta', 'gamma'])));
265265
self::assertTrue(Set::ofAll(['alpha', 'beta', 'gamma'])->removeAll(Set::ofAll(['1', '2', 'gamma']))->equals(Set::ofAll(['alpha', 'beta'])));
266266
}
267+
268+
public function testSetDisjoint()
269+
{
270+
self::assertTrue(Set::of('a', 'b', 'c')->disjoint(Set::empty()));
271+
self::assertTrue(Set::empty()->disjoint(Set::of('a', 'b', 'c')));
272+
self::assertTrue(Set::of('a', 'b', 'c')->disjoint(Set::of('d', 'e', 'f')));
273+
274+
self::assertFalse(Set::of('a', 'b', 'c')->disjoint(Set::of('a', 'e', 'f')));
275+
self::assertFalse(Set::of('a', 'b', 'c')->disjoint(Set::of('d', 'b', 'f')));
276+
self::assertFalse(Set::of('a', 'b', 'c')->disjoint(Set::of('d', 'e', 'c')));
277+
}
267278
}

0 commit comments

Comments
 (0)