Skip to content

Commit

Permalink
Add throttle method to LazyCollection (#51060)
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Apr 15, 2024
1 parent 119ab57 commit 19c6554
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions LazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,28 @@ public function tapEach(callable $callback)
});
}

/**
* Throttle the values, releasing them at most once per the given seconds.
*
* @return static<TKey, TValue>
*/
public function throttle(float $seconds)
{
return new static(function () use ($seconds) {
$microseconds = $seconds * 1_000_000;

foreach ($this as $key => $value) {
$fetchedAt = $this->preciseNow();

yield $key => $value;

$sleep = $microseconds - ($this->preciseNow() - $fetchedAt);

$this->usleep((int) $sleep);
}
});
}

/**
* Flatten a multi-dimensional associative array with dots.
*
Expand Down Expand Up @@ -1781,4 +1803,32 @@ protected function now()
? Carbon::now()->timestamp
: time();
}

/**
* Get the precise current time.
*
* @return float
*/
protected function preciseNow()
{
return class_exists(Carbon::class)
? Carbon::now()->getPreciseTimestamp()
: microtime(true) * 1_000_000;
}

/**
* Sleep for the given amount of microseconds.
*
* @return void
*/
protected function usleep(int $microseconds)
{
if ($microseconds <= 0) {
return;
}

class_exists(Sleep::class)
? Sleep::usleep($microseconds)
: usleep($microseconds);
}
}

0 comments on commit 19c6554

Please sign in to comment.