Lua 원장 이식하기
Coddy의 Lua 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.
챌린지
쉬움아래의 완전한 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 값 하나를 읽고, 여러분의 함수를 호출한 다음, 마지막에 줄바꿈 하나를 붙여 공백이 없는 JSON을 출력합니다. solve 안에서 출력하지 마세요.
직접 해보기
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 입력됩니다. 데이터를 반환하고, solve 내부에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
Lua 개발자를 위한 JavaScript의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러