Skip to content

Commit

Permalink
Set::distinctBy(), Stream::distinctBy() added and tested.
Browse files Browse the repository at this point in the history
  • Loading branch information
Smoren committed Apr 18, 2023
1 parent 4dd3aff commit a2f8758
Show file tree
Hide file tree
Showing 4 changed files with 778 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/Set.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,35 @@ public static function distinct(iterable $data, bool $strict = true): \Generator
}
}

/**
* Iterate only the distinct elements using $compareBy function for getting comparable value.
*
* Supports only strict-type comparisons:
* - scalars: compares strictly by type
* - objects: always treats different instances as not equal to each other
* - arrays: compares serialized
*
* @template T
*
* @param iterable<T> $data
* @param callable $compareBy
*
* @return \Generator<T>
*/
public static function distinctBy(iterable $data, callable $compareBy): \Generator
{
$map = [];

foreach ($data as $datum) {
$hash = UniqueExtractor::getString($compareBy($datum), true);

if (!isset($map[$hash])) {
$map[$hash] = true;
yield $datum;
}
}
}

/**
* Iterates the intersection of iterables in strict type mode.
*
Expand Down
22 changes: 22 additions & 0 deletions src/Stream.php
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,28 @@ public function distinct(bool $strict = true): self
return $this;
}

/**
* Filter out elements from the iterable source only returning unique elements.
*
* Using $compareBy function for getting comparable value.
*
* Supports only strict-type comparisons:
* - scalars: compares strictly by type
* - objects: always treats different instances as not equal to each other
* - arrays: compares serialized
*
* @param callable $compareBy
*
* @return $this
*
* @see Single::distinctBy()
*/
public function distinctBy(callable $compareBy): self
{
$this->iterable = Set::distinctBy($this->iterable, $compareBy);
return $this;
}

/**
* Cycle through the elements of iterable source sequentially forever
*
Expand Down
Loading

0 comments on commit a2f8758

Please sign in to comment.