← Lua Academy

Capstones · 68 / 69

Build an inventory decision

YOUR TASK

Make this happen

3 steps
  1. Build a pure allocation function. For each line, allocate the smaller of requested and available, never a negative amount. Return allocations in input order and the total allocated quantity. Keep the input unchanged.

  2. Read the cases in lesson.test.lua, then choose Check solution to see what needs to change.

  3. Update subject.lua until every test passes. Keep the supplied tests unchanged.

Read the starter and tests

subject.lua

type Line = { requested: number, available: number }
exports.allocate = function(lines: { Line })
  return { allocations = {}, total = 0 }
end

lesson.test.lua

local t = require("test")
local subject = require("cococo.subject")
t.it("mixed availability", function()
  local s = subject.load()
  t.expect(s.allocate({
    { requested = 5, available = 3 },
    { requested = 2, available = 9 },
    { requested = 3, available = -1 },
  })):deep_eq({ allocations = { 3, 2, 0 }, total = 5 })
end)
t.it("empty request", function()
  local s = subject.load()
  local result = s.allocate({})
  t.expect(#result.allocations):eq(0)
  t.expect(result.total):eq(0)
end)
t.it("input preserved", function()
  local s = subject.load()
  local lines = { { requested = 5, available = 3 } }
  s.allocate(lines)
  t.expect(lines[1].requested):eq(5)
end)