Menu
CoddyTech

Final: Port a Ledger

Lesson 47 of 48 in Coddy's Dart for Lua Developers course.

challenge icon

Challenge

Easy

Port the source reference program. Implement Ledger() with bool change(String name,int delta), int? get(String name), and List<String> report(). Missing names start at zero for changes; reject a negative resulting balance without mutation. Successful zero changes create entries. Report only positive balances, sorted by name as name=value. Input lines are add name delta, get name, or report, with ASCII names and signed integers whose sums fit one million. Each add emits lowercase Boolean text; get emits value or missing; report emits comma-separated entries or empty. No commands yields empty. Keep the public APIs usable independently.

Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.

Your code goes in Ledger.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.

Complete Lua reference program:

local Ledger = {}
Ledger.__index = Ledger
function Ledger.new() return setmetatable({balances = {}}, Ledger) end
function Ledger:change(name, delta)
  local value = (self.balances[name] or 0) + delta
  if value < 0 then return false end
  self.balances[name] = value
  return true
end
function Ledger:get(name) return self.balances[name] end
function Ledger:report()
  local keys, result = {}, {}
  for name, value in pairs(self.balances) do
    if value > 0 then keys[#keys + 1] = name end
  end
  table.sort(keys)
  for _, name in ipairs(keys) do
    result[#result + 1] = name .. '=' .. self.balances[name]
  end
  return result
end
local ledger, output = Ledger.new(), {}
for line in io.lines() do
  local parts = {}
  for part in line:gmatch('%S+') do parts[#parts + 1] = part end
  if parts[1] == 'add' then
    output[#output + 1] = tostring(ledger:change(parts[2], tonumber(parts[3])))
  elseif parts[1] == 'get' then
    local value = ledger:get(parts[2])
    output[#output + 1] = value == nil and 'missing' or tostring(value)
  elseif parts[1] then
    local rows = ledger:report()
    output[#output + 1] = #rows == 0 and 'empty' or table.concat(rows, ',')
  end
end
print(#output == 0 and 'empty' or table.concat(output, '\n'))

Try it yourself

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Ledger.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final l=Ledger();check(l.change('a',4)&&!l.change('a',-5)&&l.get('a')==4);check(l.change('z',0)&&l.get('z')==0&&l.get('missing')==null);check(l.report().join(',')=='a=4');
stdout.writeln(solve(input));
}

All lessons in Dart for Lua Developers

Practice on your own: Online Dart compiler