Skip to content

Commit 16bd112

Browse files
committed
Merge branch '8.x'
# Conflicts: # CHANGELOG-6.x.md # CHANGELOG-8.x.md # composer.json # src/Illuminate/Database/Schema/Grammars/MySqlGrammar.php # src/Illuminate/Database/Schema/Grammars/SQLiteGrammar.php # src/Illuminate/Foundation/Application.php # src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php
2 parents 4c26d37 + fe4a744 commit 16bd112

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

Collection.php

+16
Original file line numberDiff line numberDiff line change
@@ -959,6 +959,22 @@ public function shuffle($seed = null)
959959
return new static(Arr::shuffle($this->items, $seed));
960960
}
961961

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+
962978
/**
963979
* Skip the first {$count} items.
964980
*

LazyCollection.php

+39
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,45 @@ public function shuffle($seed = null)
920920
return $this->passthru('shuffle', func_get_args());
921921
}
922922

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+
923962
/**
924963
* Skip the first {$count} items.
925964
*

0 commit comments

Comments
 (0)