Menu
CoddyTech

Port a JavaScript Inventory

Lesson 47 of 48 in Coddy's Lua for JavaScript Developers course.

challenge icon

Challenge

Medium

Port the reference JavaScript program into Lua modules. Each input line is a lowercase ASCII name, a colon, and a signed integer delta. Aggregate by name, retain only positive final totals, sort names ascending and return name=total entries joined by commas. Return empty when none remain. Implement inventory.aggregate(lines) in inventory.lua; app formats the result. All input lines are well-formed.

JavaScript reference

const fs=require("node:fs");
const raw=fs.readFileSync(0,"utf8");
const lines=raw.length ? raw.replace(/\n$/, "").split("\n") : [];
const counts=new Map();
for (const line of lines) {
  const [name, delta]=line.split(":");
  counts.set(name,(counts.get(name) ?? 0)+Number(delta));
}
const rows=[...counts.keys()].sort().filter(name=>counts.get(name)>0).map(name=>name+"="+counts.get(name));
console.log(rows.length ? rows.join(",") : "empty");

Edit app.lua, inventory.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.

Public API checks: inventory.aggregate(lines) returns a fresh table of summed signed deltas, retaining zero totals. Empty input yields an empty table. Formatting and filtering happen in app. The locked driver checks this behavior before calling app.run. These checks print nothing when successful.

Try it yourself

-- Public API checks
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

All lessons in Lua for JavaScript Developers

Practice on your own: Online Lua compiler