Menu
CoddyTech

העבר יומן חשבונות שנכתב ב-Lua

שיעור 47 מתוך 48 בקורס JavaScript למפתחי Lua של Coddy.

challenge icon

אתגר

קל

העבירו את תוכנית העזר המלאה ב-Lua שלהלן ל-JavaScript. הקלט הוא מערך של זוגות [name, quantity]. השמות הם מחרוזות ASCII והכמויות הן מספרים שלמים. סכמו כל עדכון לפי שם, כולל סכומי ביניים שליליים. השאירו רק סכומים סופיים חיוביים והחזירו זוגות [name, total] ממוינים לפי סדר שמות ASCII. השתמשו ב-Map כדי ששמות דמויי אבטיפוס יעבדו. כל הכמויות בקלט וסכומי הביניים נשארים בטווח המספרים השלמים הבטוחים של JavaScript. קלט ריק או מצב שבו אין סכומים חיוביים מחזירים [].

תוכנית העזר ב-Lua משתמשת בטבלה לסכומים, אוספת שמות וממיינת אותם במפורש. מתאם ה-JSON הכלול מטפל בקלט המתועד של שמות ASCII וזוגות מספרים שלמים בלי מודול Lua של צד שלישי. 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 שלו. מנהל ההתקן הנעול הגלוי קורא ערך JSON אחד, קורא לפונקציה שלכם ומדפיס JSON קומפקטי עם שורה חדשה אחת בסוף. אל תדפיסו בתוך solve.

נסו בעצמכם

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// ערך JSON יחיד מתקבל ב־stdin. החזירו נתונים; אל תדפיסו בתוך solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

כל השיעורים ביחידה JavaScript למפתחי Lua

תרגלו בעצמכם: קומפיילר JavaScript אונליין