Menu
CoddyTech

Luau 장부 포팅하기

Coddy의 Luau 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

쉬움

아래의 Luau 참조 프로그램 전체를 JavaScript로 옮기세요. 입력은 [name, quantity] 쌍으로 이루어진 배열입니다. 이름은 ASCII 문자열이고 수량은 정수입니다. 중간 합계가 음수인 경우를 포함해 이름별로 모든 업데이트를 합산하세요. 최종 합계가 양수인 항목만 남기고, ASCII 이름 순서로 정렬된 [name, total] 쌍을 반환하세요. 프로토타입과 비슷한 이름도 작동하도록 Map을 사용하세요. 모든 입력 수량과 중간 합계는 JavaScript의 안전한 정수 범위 내에 있습니다. 입력이 비어 있거나 양수인 합계가 없으면 []를 반환하세요.

Luau 참조 프로그램은 합계를 저장하는 데 테이블을 사용하고, 이름을 모은 뒤 명시적으로 정렬합니다. 포함된 JSON 어댑터는 문서화된 ASCII 이름 및 정수 쌍 입력을 처리합니다. 제공된 Luau 실행기는 표준 입력을 위해 io.read를 제공하며, 이는 범용 Luau 라이브러리가 아니라 호스트 확장 기능입니다. 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)));

Luau 개발자를 위한 JavaScript의 모든 레슨

직접 연습해 보세요: 온라인 JavaScript 컴파일러