Menu
CoddyTech

Luaの台帳を移植する

Coddyの「Lua開発者のためのJavaScript」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

以下のLuaリファレンスプログラム全体をJavaScriptに移植してください。入力は[name, quantity]ペアの配列です。名前はASCII文字列、数量は整数です。負の中間合計も含め、名前ごとにすべての更新を合計してください。最終合計が正のものだけを残し、ASCIIの名前順に並べた[name, total]ペアを返してください。プロトタイプに似た名前も機能するようにMapを使ってください。入力数量と中間合計はすべてJavaScriptの安全な整数範囲内に収まります。入力が空、または正の合計がない場合は[]を返してください。

Luaのリファレンスでは合計にテーブルを使い、名前を集めて明示的に並べ替えます。付属のJSONアダプターは、サードパーティ製Luaモジュールを使わず、文書化されたASCII名と整数ペアの入力を処理します。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値を1つ読み込み、あなたの関数を呼び出し、最後に改行を1つ付けてコンパクトなJSONを出力します。solveの中で出力しないでください。

自分で試してみよう

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin から JSON 値を1つ受け取ります。データを返し、solve 内では出力しないでください。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Lua開発者のためのJavaScriptのすべてのレッスン

自分で練習してみよう: JavaScriptオンラインコンパイラ