Menu
CoddyTech

移植一个 Lua 账本

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

challenge icon

挑战

简单

将下面完整的 Lua 参考程序移植到 JavaScript。输入是由 [name, quantity] 对组成的数组。名称是 ASCII 字符串,数量是整数。按名称累计每次更新,包括中间的负数总和。只保留最终总和为正的项,并按 ASCII 名称顺序排序后返回 [name, total] 对。使用 Map,这样类似原型的名称也能正常处理。所有输入数量和中间总和都在 JavaScript 安全整数范围内。输入为空或没有正数总和时,返回 []。

Lua 参考程序使用表来存储总和,收集名称,并显式排序。它附带的 JSON 适配器无需第三方 Lua 模块,即可处理文档说明的 ASCII 名称和整数对输入。JavaScript 在锁定的驱动程序中使用内置 JSON,并使用 Map 安全地处理任意名称,包括类似原型的名称。两个版本都会将所有输入数量和中间总和限制在安全整数范围内,先累计再筛选,并返回紧凑的 JSON。

-- A small adapter for this contract only: arrays of [ASCII name, integer] pairs.
-- It is not a general-purpose JSON parser. Input is documented as well-formed.
local text = io.read("*a")
local position = 1
local function space()
    while text:sub(position, position):match("%s") do position = position + 1 end
end
local function take(character)
    space()
    assert(text:sub(position, position) == character)
    position = position + 1
end
local escapes = {['"'] = '"', ['\\'] = '\\', ['/'] = '/',
    b = '\b', f = '\f', n = '\n', r = '\r', t = '\t'}
local function name_string()
    take('"')
    local parts = {}
    while true do
        local character = text:sub(position, position)
        assert(character ~= "", "unterminated name")
        position = position + 1
        if character == '"' then break end
        if character == '\\' then
            local kind = text:sub(position, position)
            position = position + 1
            if kind == 'u' then
                local value = tonumber(text:sub(position, position + 3), 16)
                assert(value and value <= 127, "ASCII name required")
                character = string.char(value)
                position = position + 4
            else
                character = assert(escapes[kind], "invalid escape")
            end
        end
        parts[#parts + 1] = character
    end
    return table.concat(parts)
end
local function integer()
    space()
    local token = text:sub(position):match("^-?%d+%.?%d*[eE]?[+-]?%d*")
    assert(token, "integer required")
    position = position + #token
    local value = assert(tonumber(token))
    assert(value == math.floor(value) and math.abs(value) <= 9007199254740991)
    return value
end
local totals = {}
take('[')
space()
if text:sub(position, position) ~= ']' then
    while true do
        take('[')
        local name = name_string()
        take(',')
        local quantity = integer()
        take(']')
        totals[name] = (totals[name] or 0) + quantity
        space()
        if text:sub(position, position) ~= ',' then break end
        position = position + 1
    end
end
take(']')
space()
assert(position > #text, "unexpected trailing input")
local encoded_escapes = {['"'] = '\\"', ['\\'] = '\\\\',
    ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t'}
local function quote(value)
    local parts = {'"'}
    for i = 1, #value do
        local character = value:sub(i, i)
        local byte = character:byte()
        parts[#parts + 1] = encoded_escapes[character]
            or ((byte < 32 or byte == 127) and string.format('\\u%04x', byte) or character)
    end
    parts[#parts + 1] = '"'
    return table.concat(parts)
end
local names = {}
for name, total in pairs(totals) do
    if total > 0 then names[#names + 1] = name end
end
table.sort(names)
local result = {}
for _, name in ipairs(names) do
    result[#result + 1] = '[' .. quote(name) .. ',' .. string.format('%.0f', totals[name]) .. ']'
end
print('[' .. table.concat(result, ',') .. ']')

编辑 exercise.js,并保留其中的 solve 导出。可见的锁定文件 driver.js 会读取一个 JSON 值,调用你的函数,并以紧凑的 JSON 格式打印结果,末尾带一个换行符。不要在 solve 中打印内容。

亲手试试

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// 从 stdin 读取一个 JSON 值。返回数据;不要在 solve 中打印。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

面向 Lua 开发者的 JavaScript中的所有课

自己练习: JavaScript 在线编译器