Final: Port a Ledger
Lesson 47 of 48 in Coddy's Dart for Go Developers course.
Challenge
EasyPort 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 Go reference program:
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
type Ledger struct{ balances map[string]int }
func newLedger() *Ledger { return &Ledger{balances: map[string]int{}} }
func (l *Ledger) change(name string, delta int) bool {
value := l.balances[name] + delta
if value < 0 {
return false
}
l.balances[name] = value
return true
}
func (l *Ledger) get(name string) (int, bool) {
value, ok := l.balances[name]
return value, ok
}
func (l *Ledger) report() []string {
names := make([]string, 0, len(l.balances))
for name, value := range l.balances {
if value > 0 {
names = append(names, name)
}
}
sort.Strings(names)
out := make([]string, len(names))
for i, name := range names {
out[i] = name + "=" + strconv.Itoa(l.balances[name])
}
return out
}
func main() {
in := bufio.NewScanner(os.Stdin)
ledger := newLedger()
var out []string
for in.Scan() {
a := strings.Fields(in.Text())
if len(a) == 0 {
continue
}
switch a[0] {
case "add":
delta, _ := strconv.Atoi(a[2])
out = append(out, strconv.FormatBool(ledger.change(a[1], delta)))
case "get":
if n, ok := ledger.get(a[1]); ok {
out = append(out, strconv.Itoa(n))
} else {
out = append(out, "missing")
}
default:
if r := ledger.report(); len(r) == 0 {
out = append(out, "empty")
} else {
out = append(out, strings.Join(r, ","))
}
}
}
if len(out) == 0 {
fmt.Println("empty")
} else {
fmt.Println(strings.Join(out, "\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 Go Developers
1First Dart Programs
Run Dart FilesOutput and CommentsImports and LibrariesBindings and TypesNumeric OperationsRecap: Parcel Invoice4Collection Pipelines
Iterables and LazinessMaps and Missing KeysSets and MembershipClosures and CallbacksSorting and ComparatorsRecap: Word Inventory3Functions and Values
Functions and ReturnsNamed ParametersNull SafetyStrings and UnicodeLists and MutationRecap: Record Readings6Objects and State
Classes and InstancesConstructors and FactoriesProperties and PrivacyIdentity and CopiesComposition Across FilesRecap: Bounded Counter9Parcel Depot Project
Depot: Valid ItemsDepot: Register StockPractice on your own: Online Dart compiler