DataStreamTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php declare(strict_types=1);
  2. /**
  3. * This file is part of toolkit/stdlib.
  4. *
  5. * @author https://github.com/inhere
  6. * @link https://github.com/php-toolkit/stdlib
  7. * @license MIT
  8. */
  9. namespace Toolkit\StdlibTest\Util\Stream;
  10. use Toolkit\Stdlib\Util\Stream\DataStream;
  11. use Toolkit\StdlibTest\BaseLibTestCase;
  12. use function vdump;
  13. use const SORT_NUMERIC;
  14. /**
  15. * Class DataStreamTest
  16. *
  17. * @package Toolkit\StdlibTest\Util\Stream
  18. */
  19. class DataStreamTest extends BaseLibTestCase
  20. {
  21. public array $tests = [
  22. 90, 19, 34, 8, 17
  23. ];
  24. public function testSorted(): void
  25. {
  26. $ds = DataStream::of([
  27. 34, 90, 19, 8, 17
  28. ]);
  29. vdump($ds->toArray());
  30. $new = $ds->sorted();
  31. vdump($new->toArray());
  32. $this->assertNotEmpty($new->toArray());
  33. $this->assertEquals(8, $new->findFirst()->get());
  34. $this->assertEquals(90, $new->findLast()->get());
  35. $this->assertEquals(34, $ds->findFirst()->get());
  36. $new = $ds->sorted(DataStream::intComparer(true));
  37. $this->assertNotEmpty($new->toArray());
  38. vdump($new->toArray());
  39. $this->assertEquals(8, $new->findLast()->get());
  40. $this->assertEquals(90, $new->findFirst()->get());
  41. }
  42. public function testDistinct(): void
  43. {
  44. $ds = DataStream::of([
  45. 34, 90, 19, 90, 34
  46. ]);
  47. $new = $ds->distinct(SORT_NUMERIC);
  48. // vdump($new->toArray());
  49. $this->assertCount(3, $new);
  50. }
  51. public function testMaxMin(): void
  52. {
  53. $ds = DataStream::of([
  54. 34, 90, 19, 8, 17
  55. ]);
  56. $ret = $ds->max(DataStream::intComparer());
  57. $this->assertEquals(90, $ret->get());
  58. $ret = $ds->min(DataStream::intComparer());
  59. $this->assertEquals(8, $ret->get());
  60. }
  61. public function testMap(): void
  62. {
  63. $ds = DataStream::of([
  64. 34, 90, 19, 8, 17
  65. ]);
  66. $new = $ds->map('strval');
  67. vdump($ds->toArray(), $new->toArray());
  68. $this->assertNotEmpty($ret = $new->toArray());
  69. $this->assertEquals(['34', '90', '19', '8', '17'], $ret);
  70. }
  71. public function testFlatMap(): void
  72. {
  73. $ds = DataStream::of([
  74. [34, 90],
  75. [19, 8, 17],
  76. ]);
  77. $new = $ds->flatMap(function (array $item) {
  78. return $item;
  79. });
  80. vdump($ds->toArray(), $new->toArray());
  81. $this->assertNotEmpty($ret = $new->toArray());
  82. $this->assertEquals([34, 90, 19, 8, 17], $ret);
  83. }
  84. }