diff --git a/compcount.lua b/compcount.lua index 2944a9c..a6aaeeb 100644 --- a/compcount.lua +++ b/compcount.lua @@ -273,6 +273,26 @@ local function getMeItemCount(itemId) return 0 end +local function listBridgeItems(bridge) + local listItems = bridge.listItems or bridge.getItems or bridge.listAvailableItems + + if not listItems then + return nil + end + + local ok, items = pcall(listItems, {}) + if ok and type(items) == "table" then + return items + end + + ok, items = pcall(listItems) + if ok and type(items) == "table" then + return items + end + + return nil +end + local function getMeItemCounts(itemIds) local counts = {} @@ -286,46 +306,23 @@ local function getMeItemCounts(itemIds) return counts end - local unresolved = {} - local unresolvedCount = 0 + local snapshot = listBridgeItems(bridge) + if not snapshot then + return counts + end + + local wanted = {} for i = 1, #itemIds do - local itemId = itemIds[i] - local count = getMeItemCount(itemId) - counts[itemId] = count - - if count == 0 then - unresolved[itemId] = true - unresolvedCount = unresolvedCount + 1 - end + wanted[itemIds[i]] = true end - if unresolvedCount == 0 then - return counts - end - - local listItems = bridge.listItems or bridge.getItems or bridge.listAvailableItems - if not listItems then - return counts - end - - local ok, items = pcall(listItems) - if not ok or type(items) ~= "table" then - return counts - end - - for i = 1, #items do - local item = items[i] + for i = 1, #snapshot do + local item = snapshot[i] local itemId = item and (item.name or item.id or item.item_id) - if itemId and unresolved[itemId] then + if itemId and wanted[itemId] then counts[itemId] = tonumber(item.amount or item.count or item.qty) or 0 - unresolved[itemId] = nil - unresolvedCount = unresolvedCount - 1 - - if unresolvedCount == 0 then - break - end end end @@ -345,9 +342,15 @@ end local function createAsyncMeItemCountsJob(itemIds, batchSize) local counts = makeZeroCounts(itemIds) local index = 1 + local snapshot + local wanted = {} batchSize = math.max(1, math.floor(tonumber(batchSize) or 1)) + for i = 1, #itemIds do + wanted[itemIds[i]] = true + end + return { step = function() local bridge = ensureStorageBridge() @@ -356,14 +359,23 @@ local function createAsyncMeItemCountsJob(itemIds, batchSize) return true, counts end - local lastIndex = math.min(#itemIds, index + batchSize - 1) + if not snapshot then + snapshot = listBridgeItems(bridge) or {} + end + + local lastIndex = math.min(#snapshot, index + batchSize - 1) for i = index, lastIndex do - counts[itemIds[i]] = getMeItemCount(itemIds[i]) + local item = snapshot[i] + local itemId = item and (item.name or item.id or item.item_id) + + if itemId and wanted[itemId] then + counts[itemId] = tonumber(item.amount or item.count or item.qty) or 0 + end end index = lastIndex + 1 - return index > #itemIds, counts + return index > #snapshot, counts end, } end