Menu
CoddyTech

Portiere ein Luau-Kassenbuch

Lektion 47 von 48 im Kurs JavaScript für Luau-Entwickler von Coddy.

challenge icon

Aufgabe

Einfach

Übertrage das vollständige Luau-Referenzprogramm unten nach JavaScript. Die Eingabe ist ein Array aus [name, quantity]-Paaren. Namen sind ASCII-Zeichenketten und Mengen sind Ganzzahlen. Addiere jedes Update nach Namen, einschließlich negativer Zwischensummen. Behalte nur positive Endsummen und gib [name, total]-Paare zurück, sortiert nach ASCII-Namensreihenfolge. Verwende eine Map, damit auch Namen funktionieren, die Prototypen ähneln. Alle Eingabemengen und Zwischensummen bleiben innerhalb des sicheren Ganzzahlbereichs von JavaScript. Bei leerer Eingabe oder wenn es keine positiven Summen gibt, wird [] zurückgegeben.

Die Luau-Referenz verwendet eine Tabelle für Summen, sammelt Namen und sortiert sie ausdrücklich. Ihr enthaltener JSON-Adapter verarbeitet die dokumentierte Eingabe aus ASCII-Namen und Ganzzahlpaaren. Der bereitgestellte Luau-Runner stellt io.read für die Standardeingabe bereit; dies ist eine Host-Erweiterung und keine universelle Luau-Bibliothek. JavaScript verwendet das integrierte JSON im gesperrten Treiber und eine Map für beliebige Namen, auch solche, die Prototypen ähneln. Beide Versionen beschränken alle Eingabemengen und Zwischensummen auf den sicheren Ganzzahlbereich, aggregieren vor dem Filtern und geben kompaktes JSON zurück.

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

Bearbeite exercise.js und behalte dessen solve-Export bei. Der sichtbare gesperrte driver.js liest einen JSON-Wert ein, ruft deine Funktion auf und gibt kompaktes JSON mit genau einem abschließenden Zeilenumbruch aus. Gib nichts innerhalb von solve aus.

Probier es selbst

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Ein JSON-Wert kommt über stdin an. Gib Daten zurück; gib innerhalb von solve nichts aus.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Alle Lektionen in JavaScript für Luau-Entwickler

Übe selbstständig: Online-JavaScript-Compiler