Menu
CoddyTech

Chuyển sổ cái sang Lua

Bài học 47 trên 48 trong khóa học JavaScript dành cho nhà phát triển Lua của Coddy.

challenge icon

Thử thách

Dễ

Chuyển toàn bộ chương trình tham khảo bằng Lua dưới đây sang JavaScript. Đầu vào là một mảng gồm các cặp [name, quantity]. Tên là chuỗi ASCII, còn số lượng là số nguyên. Cộng mọi lần cập nhật theo tên, bao gồm cả các tổng trung gian âm. Chỉ giữ lại các tổng cuối cùng dương và trả về các cặp [name, total], được sắp xếp theo thứ tự tên ASCII. Dùng Map để các tên giống thuộc tính nguyên mẫu vẫn hoạt động. Tất cả số lượng đầu vào và tổng trung gian đều nằm trong phạm vi số nguyên an toàn của JavaScript. Đầu vào rỗng hoặc không có tổng dương thì trả về [].

Chương trình tham khảo bằng Lua dùng một bảng để lưu tổng, thu thập tên và sắp xếp chúng một cách tường minh. Bộ chuyển đổi JSON đi kèm xử lý đầu vào gồm các cặp tên ASCII và số nguyên như đã mô tả mà không cần module Lua của bên thứ ba. JavaScript dùng JSON tích hợp sẵn trong driver bị khóa và dùng Map để xử lý an toàn các tên tùy ý, kể cả tên giống thuộc tính nguyên mẫu. Cả hai phiên bản đều giới hạn mọi số lượng đầu vào và tổng trung gian trong phạm vi số nguyên an toàn, gộp các giá trị trước khi lọc và trả về JSON gọn.

-- 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, ',') .. ']')

Chỉnh sửa exercise.js và giữ lại phần export solve. Tệp driver.js bị khóa hiển thị sẽ đọc một giá trị JSON, gọi hàm của bạn và in JSON gọn với một ký tự xuống dòng ở cuối. Đừng in gì bên trong solve.

Tự làm thử

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Một giá trị JSON được nhập qua stdin. Trả về dữ liệu, đừng in ra trong solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Tất cả bài học trong JavaScript dành cho nhà phát triển Lua

Tự luyện tập: Trình biên dịch JavaScript online