הסבת פנקס חשבונות ב-Luau
שיעור 47 מתוך 48 בקורס JavaScript למפתחי Luau של Coddy.
אתגר
קלהעבירו את תוכנית הייחוס המלאה של Luau שלהלן ל-JavaScript. הקלט הוא מערך של זוגות [name, quantity]. השמות הם מחרוזות ASCII והכמויות הן מספרים שלמים. סכמו כל עדכון לפי שם, כולל סכומי ביניים שליליים. השאירו רק סכומים סופיים חיוביים והחזירו זוגות [name, total] ממוינים לפי סדר שמות ASCII. השתמשו ב-Map כדי ששמות דמויי אבטיפוס יעבדו. כל כמויות הקלט וסכומי הביניים נשארים בטווח המספרים השלמים הבטוחים של JavaScript. קלט ריק או היעדר סכומים חיוביים מחזירים [].
תוכנית הייחוס של Luau משתמשת בטבלה עבור הסכומים, אוספת שמות וממיינת אותם במפורש. מתאם JSON הכלול בה מטפל בקלט המתועד של שמות ASCII וזוגות של מספרים שלמים. מריץ Luau שסופק מספק את io.read עבור קלט סטנדרטי; זוהי הרחבה של סביבת האירוח ולא ספריית Luau אוניברסלית. 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";
// ערך JSON אחד מתקבל דרך stdin. החזירו נתונים; אל תדפיסו מתוך solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
כל השיעורים ביחידה JavaScript למפתחי Luau
1מ-Luau ל-JavaScript
הרצת JavaScriptמחיבור מחרוזות לתבניותמ-local ל-let ול-constמספרים ופענוח מפורשמ-nil לשני ערכי היעדרותחזרה: קבלה4צינורות איטרציה
while, break ו-continueצינורות סינון ומיפויצבירה וקלט ריקמיון ותוצאות Comparatorסיכום: בניית דירוג2החלטות וזרימת הביצוע
שוויון והמרה כפויהאפס משנה את ערך האמתelseif ל־else ifipairs ל־for-ofסיכום: כללי משלוחים3מטבלאות למערכים ולמפות
אינדקסים של רצפים ו-pushטבלאות רשומות לאובייקטיםטבלאות קבוצות ל-Map ול-Setעותקים שטחיים והשמהסיכום: ספירת מלאי6שגיאות ו-ES Modules
JSON ללא הערכהמ־pcall ל־try ו־catchמטבלאות מודול לייצואי ESמ־type למאמתים בזמן ריצהסיכום: אימות אצווה9פרויקט: מעבד הזמנות
יצירת מודל להזמנההחלת תמחור לחבריםתרגלו בעצמכם: קומפיילר JavaScript אונליין