Menu
CoddyTech

Bir Lua Defterini Taşıyın

Coddy'nin Lua Geliştiricileri için JavaScript kursunda ders 47 / 48.

challenge icon

Görev

Kolay

Aşağıdaki eksiksiz Lua referans programını JavaScript'e aktar. Girdi, [name, quantity] çiftlerinden oluşan bir dizidir. Adlar ASCII dizeleridir ve miktarlar tam sayıdır. Negatif ara toplamlar da dahil olmak üzere ada göre her güncellemeyi topla. Yalnızca pozitif son toplamları tut ve [name, total] çiftlerini ASCII ad sırasına göre sıralanmış olarak döndür. Prototip benzeri adların çalışması için bir Map kullan. Tüm girdi miktarları ve ara toplamlar JavaScript'in güvenli tam sayı aralığında kalır. Boş girdi veya pozitif toplam olmaması durumunda [] döndür.

Lua referansı, toplamlar için bir tablo kullanır, adları toplar ve bunları açıkça sıralar. İçindeki JSON bağdaştırıcısı, belgelenen ASCII adlı ve tam sayı çiftlerinden oluşan girdiyi üçüncü taraf bir Lua modülü olmadan işler. JavaScript, kilitli sürücüde yerleşik JSON'u ve prototip benzeri adlar da dahil olmak üzere keyfî adları güvenli biçimde işlemek için bir Map kullanır. Her iki sürüm de tüm girdi miktarlarını ve ara toplamları güvenli tam sayı aralığında tutar, filtrelemeden önce toplama yapar ve kompakt JSON döndürür.

-- 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 dosyasını düzenle ve solve dışa aktarımını koru. Görünür durumdaki kilitli driver.js, bir JSON değeri okur, işlevini çağırır ve sonunda tek bir yeni satır bulunan kompakt JSON yazdırır. solve içinde yazdırma yapma.

Kendin dene

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin üzerinden bir JSON değeri gelir. Veriyi döndürün; solve içinde çıktı yazdırmayın.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Lua Geliştiricileri için JavaScript bölümündeki tüm dersler

Kendi başına pratik yap: Online JavaScript derleyicisi