Port a Lua Ledger
Lesson 47 of 48 in Coddy's JavaScript for Lua Developers course.
Challenge
EasyPort the complete Lua reference program below to JavaScript. Input is an array of [name, quantity] pairs. Names are ASCII strings and quantities are integers. Sum every update by name, including negative intermediate totals. Keep only positive final totals and return [name, total] pairs sorted by ASCII name order. Use a Map so prototype-like names work. All input quantities and intermediate totals stay within the JavaScript safe integer range. Empty input or no positive totals returns [].
The Lua reference uses a table for totals, collects names, and explicitly sorts them. Its included JSON adapter handles the documented ASCII-name and integer-pair input without a third-party Lua module. JavaScript uses built-in JSON in the locked driver and a Map for safe arbitrary names, including prototype-like names. Both versions restrict all input quantities and intermediate totals to the safe integer range, aggregate before filtering, and return compact 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, ',') .. ']')Edit exercise.js and retain its solve export. The visible locked driver.js reads one JSON value, calls your function, and prints compact JSON with one final newline. Do not print inside solve.
Try it yourself
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// One JSON value arrives on stdin. Return data; do not print inside solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
All lessons in JavaScript for Lua Developers
1From Lua to JavaScript
Run JavaScriptConcatenation to Templateslocal to let and constNumbers and Explicit Parsingnil to Two Absence ValuesRecap: Receipt4Iteration Pipelines
while, break, and continueFilter and Map PipelinesAccumulation and Empty InputSorting and Comparator ResultsRecap: Build a Ranking2Decisions and Flow
Equality and CoercionZero Changes Truthinesselseif to else ifipairs to for-ofRecap: Shipping Rules3Tables to Arrays and Maps
Sequence Indexes and pushRecord Tables to ObjectsSet Tables to Map and SetShallow Copies and AssignmentRecap: Inventory Counts6Errors and ES Modules
JSON Without Evaluationpcall to try and catchModule Tables to ES Exportstype to Runtime ValidatorsRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler