66namespace WS \Utils \Collections ;
77
88use RuntimeException ;
9- use WS \Utils \Collections \Functions \Reorganizers ;
109
1110class SerialStream implements Stream
1211{
@@ -17,7 +16,7 @@ class SerialStream implements Stream
1716
1817 public function __construct (Collection $ collection )
1918 {
20- $ this ->list = new ArrayList ();
19+ $ this ->list = $ this -> emptyList ();
2120 $ this ->list ->addAll ($ collection );
2221 }
2322
@@ -163,17 +162,10 @@ public function sortDesc(callable $comparator): Stream
163162
164163 public function reverse (): Stream
165164 {
166- $ size = $ this ->list ->size ();
167- /** @var ListSequence $list */
168- $ list = $ this ->list ->copy ();
169- $ this ->walk (static function ($ head , $ index ) use ($ list , $ size ) {
170- $ tailIndex = $ size - $ index - 1 ;
171- $ tail = $ list ->get ($ tailIndex );
172- $ list ->set ($ tail , $ index );
173- $ list ->set ($ head , $ tailIndex );
174- }, (int )($ size /2 ));
175- $ this ->list = $ list ;
176-
165+ $ array = $ this ->list ->toArray ();
166+ $ reversedArray = array_reverse ($ array );
167+ $ this ->list = $ this ->emptyList ();
168+ $ this ->list ->addAll ($ reversedArray );
177169 return $ this ;
178170 }
179171
@@ -190,8 +182,20 @@ public function collect(callable $collector)
190182 */
191183 public function findAny ()
192184 {
193- return $ this ->reorganize (Reorganizers::random (1 ))
194- ->findFirst ();
185+ $ size = $ this ->list ->size ();
186+ if ($ size === 0 ) {
187+ return null ;
188+ }
189+ /** @noinspection PhpUnhandledExceptionInspection */
190+ $ rIndex = random_int (0 , $ size - 1 );
191+ $ pointer = 0 ;
192+ $ item = null ;
193+ foreach ($ this ->list as $ item ) {
194+ if ($ rIndex === $ pointer ++) {
195+ break ;
196+ }
197+ }
198+ return $ item ;
195199 }
196200
197201 /**
@@ -270,7 +274,7 @@ public function reduce(callable $accumulator)
270274
271275 public function getCollection (): Collection
272276 {
273- return $ this ->list ;
277+ return $ this ->list -> copy () ;
274278 }
275279
276280 private function emptyList (): Collection
0 commit comments