Skip to content

Commit 7e1b080

Browse files
committed
[Stream] Add sorted fork-operation.
1 parent 90fa1ae commit 7e1b080

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

src/Fp/Streams/Stream.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
use Fp\Operations\ReduceOperation;
4242
use Fp\Operations\RepeatNOperation;
4343
use Fp\Operations\RepeatOperation;
44+
use Fp\Operations\SortedOperation;
4445
use Fp\Operations\TailOperation;
4546
use Fp\Operations\TakeOperation;
4647
use Fp\Operations\TakeWhileOperation;
@@ -476,6 +477,16 @@ public function groupAdjacentBy(callable $discriminator): Stream
476477
}));
477478
}
478479

480+
/**
481+
* @inheritDoc
482+
* @psalm-param callable(TV, TV): int $cmp
483+
* @psalm-return self<TV>
484+
*/
485+
public function sorted(callable $cmp): self
486+
{
487+
return $this->fork(SortedOperation::of($this->emitter)($cmp));
488+
}
489+
479490
/**
480491
* @inheritDoc
481492
* @psalm-param callable(TV): bool $predicate

src/Fp/Streams/StreamChainableOps.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,4 +323,20 @@ public function chunks(int $size): Stream;
323323
* @return Stream<array{D, Seq<TV>}>
324324
*/
325325
public function groupAdjacentBy(callable $discriminator): Stream;
326+
327+
/**
328+
* Sort streamed elements
329+
*
330+
* ```php
331+
* >>> Stream::emits([2, 1, 3])->sorted(fn($lhs, $rhs) => $lhs - $rhs)->toArray();
332+
* => [1, 2, 3]
333+
*
334+
* >>> Stream::emits([2, 1, 3])->sorted(fn($lhs, $rhs) => $rhs - $lhs)->toArray();
335+
* => [3, 2, 1]
336+
* ```
337+
*
338+
* @psalm-param callable(TV, TV): int $cmp
339+
* @psalm-return Stream<TV>
340+
*/
341+
public function sorted(callable $cmp): Stream;
326342
}

tests/Runtime/Classes/Stream/StreamOpsTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,4 +243,17 @@ public function testMkString(): void
243243
$this->assertEquals('(0,1,2)', Stream::emits([0, 1, 2])->mkString('(', ',', ')'));
244244
$this->assertEquals('()', Stream::emits([])->mkString('(', ',', ')'));
245245
}
246+
247+
public function testSorted(): void
248+
{
249+
$this->assertEquals(
250+
[1, 2, 3],
251+
Stream::emits([1, 3, 2])->sorted(fn($lhs, $rhs) => $lhs - $rhs)->toArray()
252+
);
253+
254+
$this->assertEquals(
255+
[3, 2, 1],
256+
Stream::emits([1, 3, 2])->sorted(fn($lhs, $rhs) => $rhs - $lhs)->toArray()
257+
);
258+
}
246259
}

0 commit comments

Comments
 (0)