| Bytes | Lang | Time | Link |
|---|---|---|---|
| 065 | Charcoal | 250118T134059Z | Neil |
| 107 | JavaScript Node.js | 250117T153110Z | l4m2 |
Charcoal, 65 bytes
Fθ«≔⁰ζF±§ι¹«§≔ι¹¦⁰≔⊟⮌Φθ∧‹⁰§λ¹⁼§λ⁰§ι⁰η§≔η¹⊖§η¹≧⁺§η²ζ»⊞ιζ»Eθ⭆¹✂ι¹χ²
Try it online! Link is to verbose version of code. Explanation:
Fθ«
Loop over the input array.
≔⁰ζ
Start with a COGS of zero.
F±§ι¹«
If this is a sales transaction, then repeat for the unnegated quantity:
§≔ι¹¦⁰
Clear the quantity of the transaction. (This doesn't affect the loop as it's already taken a copy by this point.)
≔⊟⮌Φθ∧‹⁰§λ¹⁼§λ⁰§ι⁰η
Find a purchase transaction for this item which still has a quantity remaining.
§≔η¹⊖§η¹
Decrement the quantity remaining of the purchase.
≧⁺§η²ζ
Add the cost of the purchase to the COGS.
»⊞ιζ
Save the final COGS (if any) to the item.
»Eθ⭆¹✂ι¹χ²
Output just the remaining quantity or the COGS for each item as appropriate.
JavaScript (Node.js), 107 bytes
x=>x.map(y=([i,q],j)=>y[j]=q>0?[q,,]:[,(g=j=>q?x[j][-!y[j][0]]==i?g(j,--y[j][0],++q)+x[j][2]:g(j+1):0)(0)])
x=>x.map(y=([i,q],j)=> // y stores refs to modify
y[j]=q>0?[q,,]: // purchase
[,(g=j=>q?
x[j][-!y[j][0]]==i? // x[j][0]==i && y[j][0]
g(j,--y[j][0],++q)+x[j][2] // Buy at cost on index j
:g(j+1):0)(0)]) // else try next
Crash y[j][0]=undefined[0] in case oversell