Menu
CoddyTech

Adatta un registro contabile in Lua

Lezione 47 di 48 del corso JavaScript per sviluppatori Lua di Coddy.

challenge icon

Sfida

Facile

Converti in JavaScript il programma di riferimento completo in Lua riportato di seguito. L'input è un array di coppie [name, quantity]. I nomi sono stringhe ASCII e le quantità sono numeri interi. Somma ogni aggiornamento per nome, compresi i totali intermedi negativi. Conserva solo i totali finali positivi e restituisci coppie [name, total] ordinate in base all'ordine dei nomi ASCII. Usa una Map affinché funzionino anche i nomi simili a quelli dei prototipi. Tutte le quantità in input e i totali intermedi rimangono nell'intervallo degli interi sicuri di JavaScript. Un input vuoto o l'assenza di totali positivi restituisce [].

Il programma di riferimento in Lua usa una tabella per i totali, raccoglie i nomi e li ordina esplicitamente. Il relativo adattatore JSON incluso gestisce l'input documentato con nomi ASCII e coppie di interi senza un modulo Lua di terze parti. JavaScript usa il JSON integrato nel driver bloccato e una Map per gestire in sicurezza nomi arbitrari, compresi quelli simili a quelli dei prototipi. Entrambe le versioni limitano tutte le quantità in input e i totali intermedi all'intervallo degli interi sicuri, aggregano prima di filtrare e restituiscono JSON compatto.

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

Modifica exercise.js e mantieni la sua esportazione solve. Il driver.js visibile e bloccato legge un valore JSON, chiama la tua funzione e stampa JSON compatto con un solo a capo finale. Non stampare all'interno di solve.

Provalo tu

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Su stdin arriva un valore JSON. Restituisci i dati; non stampare nulla all'interno di solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Tutte le lezioni di JavaScript per sviluppatori Lua

Esercitati da solo: Compilatore JavaScript online