Skip to content

Commit

Permalink
Added async.Each and async.Batch functions.
Browse files Browse the repository at this point in the history
  • Loading branch information
Cidan committed Apr 14, 2024
1 parent 866b73c commit 79199ac
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions core/async.lua
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ local addon = LibStub('AceAddon-3.0'):GetAddon(addonName)
local async = addon:NewModule('Async')

-- DoWithDelay will run the coroutine function with a delay between each yield.
-- You must call async:Yield() in your function to yield when you wait for the next frame.
---@param delay number
---@param fn fun()
---@param cb fun()
Expand All @@ -37,6 +38,7 @@ function async:DoWithDelay(delay, fn, cb)
end
C_Timer.After(delay, task.worker)
end

task.worker()
end

Expand All @@ -48,6 +50,39 @@ function async:Do(fn, cb)
self:DoWithDelay(0, fn, cb)
end

--- Each will call function fn for each item in list, one call per frame.
--- Do not call async:Yield() in fn, as it will be called automatically.
---@generic T
---@param list `T`[]
---@param fn fun(item: `T`, index: number)
---@param cb fun()
function async:Each(list, fn, cb)
self:Do(function()
for i = 1, #list do
fn(list[i], i)
self:Yield()
end
end, cb)
end

-- Batch will call function fn for each item in list, with a batch size of count per frame.
-- Do not call async:Yield() in fn, as it will be called automatically.
---@generic T
---@param count number
---@param list `T`[]
---@param fn fun(item: `T`, index: number)
---@param cb fun()
function async:Batch(count, list, fn, cb)
self:Do(function()
for i = 1, #list, count do
for j = i, math.min(i + count - 1, #list) do
fn(list[j], j)
end
self:Yield()
end
end, cb)
end

-- Yield is a small wrapper around coroutine.yield.
function async:Yield()
coroutine.yield()
Expand Down

0 comments on commit 79199ac

Please sign in to comment.