Depot: Reserve Stock
Lesson 45 of 48 in Coddy's Dart for C# Developers course.
Challenge
EasyKeep previous behavior. Implement reserve: reject unknown name, negative count, or count exceeding stock without mutation. Otherwise subtract count, including zero, and return true. Input begins with the stage number on its own line. Later lines are commands: item name stock, get name, reserve name count, or report. Names are ASCII words; _ represents the empty item name. Integer magnitudes are at most 1000. Stage one reports item validity; later stages report whether add succeeds. Every item/reserve command emits lowercase Boolean text, get emits stock or missing, and report emits sorted comma-separated entries or empty. Join command results with newlines; no commands yields empty. The locked driver dispatches independent API probes by the stage in input. Implement only the new APIs, retaining all previous behavior and the stable file layout.
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 Item.dart, Depot.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.
Try it yourself
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Item.dart';
import 'Depot.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 stage=int.parse(input.split('\n').first);check(Item('x',0).valid && !Item('',2).valid && !Item('x',-1).valid);
if(stage>=2){final d=Depot();check(d.add(Item('a',4))&&!d.add(Item('a',9))&&!d.add(Item('b',-1)));check(d.stock('a')==4 && d.stock('none')==null);if(stage>=3){check(d.reserve('a',3)&&d.stock('a')==1);check(!d.reserve('a',2)&&!d.reserve('a',-1)&&!d.reserve('none',0)&&d.stock('a')==1);}if(stage>=4){check(d.add(Item('b',0)));check(d.report().join(',')=='a=1,b=0');d.report().clear();check(d.report().length==2);}}
stdout.writeln(solve(input));
}
All lessons in Dart for C# 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