Menu
CoddyTech

移植物品栏

Coddy 面向 JavaScript 开发者的 Luau 课程 课程的第 47 课,共 48 课。

challenge icon

挑战

中等

将参考的 JavaScript 程序移植到 Luau 模块中。每个输入行均由小写 ASCII 名称、冒号和带符号整数增量组成。按名称进行汇总,仅保留最终总数为正数的记录,按名称升序排序,并返回用逗号分隔的 name=total 条目。如果没有剩余项目,则返回 empty。在 inventory.luau 中实现 inventory.aggregate(lines);app 负责格式化结果。所有输入行格式均正确。

JavaScript 参考代码

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");

编辑 app.luau 和 inventory.luau。可见且锁定的 main.luau 会从标准输入读取数据并转换为行序列,调用 app.run(lines),并在最后附带一个换行符打印其返回值。请勿打印诊断信息或更改模块名称。空输入将产生空序列。所有数值输入都足够小,不会发生溢出。

公共 API 检查:inventory.aggregate(lines) 会返回一个包含带符号增量求和结果的新表,并保留总数为零的记录。空输入将返回一个空表。格式化和过滤在 app 中进行。锁定的驱动代码会在调用 app.run 之前检查此行为。检查成功时不会打印任何内容。

亲手试试

-- 公开 API 检查
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))

面向 JavaScript 开发者的 Luau 课程中的所有课

自己练习: Luau 在线编译器