File tree 2 files changed +55
-0
lines changed
2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -959,6 +959,22 @@ public function shuffle($seed = null)
959
959
return new static (Arr::shuffle ($ this ->items , $ seed ));
960
960
}
961
961
962
+ /**
963
+ * Create chunks representing a "sliding window" view of the items in the collection.
964
+ *
965
+ * @param int $size
966
+ * @param int $step
967
+ * @return static
968
+ */
969
+ public function sliding ($ size = 2 , $ step = 1 )
970
+ {
971
+ $ chunks = floor (($ this ->count () - $ size ) / $ step ) + 1 ;
972
+
973
+ return static ::times ($ chunks , function ($ number ) use ($ size , $ step ) {
974
+ return $ this ->slice (($ number - 1 ) * $ step , $ size );
975
+ });
976
+ }
977
+
962
978
/**
963
979
* Skip the first {$count} items.
964
980
*
Original file line number Diff line number Diff line change @@ -920,6 +920,45 @@ public function shuffle($seed = null)
920
920
return $ this ->passthru ('shuffle ' , func_get_args ());
921
921
}
922
922
923
+ /**
924
+ * Create chunks representing a "sliding window" view of the items in the collection.
925
+ *
926
+ * @param int $size
927
+ * @param int $step
928
+ * @return static
929
+ */
930
+ public function sliding ($ size = 2 , $ step = 1 )
931
+ {
932
+ return new static (function () use ($ size , $ step ) {
933
+ $ iterator = $ this ->getIterator ();
934
+
935
+ $ chunk = [];
936
+
937
+ while ($ iterator ->valid ()) {
938
+ $ chunk [$ iterator ->key ()] = $ iterator ->current ();
939
+
940
+ if (count ($ chunk ) == $ size ) {
941
+ yield tap (new static ($ chunk ), function () use (&$ chunk , $ step ) {
942
+ $ chunk = array_slice ($ chunk , $ step , null , true );
943
+ });
944
+
945
+ // If the $step between chunks is bigger than each chunk's $size
946
+ // we will skip the extra items (which should never be in any
947
+ // chunk) before we continue to the next chunk in the loop.
948
+ if ($ step > $ size ) {
949
+ $ skip = $ step - $ size ;
950
+
951
+ for ($ i = 0 ; $ i < $ skip && $ iterator ->valid (); $ i ++) {
952
+ $ iterator ->next ();
953
+ }
954
+ }
955
+ }
956
+
957
+ $ iterator ->next ();
958
+ }
959
+ });
960
+ }
961
+
923
962
/**
924
963
* Skip the first {$count} items.
925
964
*
You can’t perform that action at this time.
0 commit comments