Port a Dart Ledger
Lesson 47 of 48 in Coddy's JavaScript for Dart Developers course.
Challenge
EasyPort the accompanying Dart ledger reference to JavaScript. Input is one JSON array of [name, quantity] pairs. Names contain only ASCII characters; quantities are integers, and all computed totals stay within the JavaScript safe-integer range. Sum every update by name, retaining negative intermediate totals. After aggregation, keep only positive totals, sort names by ASCII order, and return [name, total] pairs. Use a Map so names such as __proto__ remain ordinary data. Do not filter updates before aggregation.
Implement the solve export in exercise.js. The locked driver.js parses standard input and serializes the returned data as JSON with a final newline. Do not print diagnostics. The complete source reference below has its own stdin entry point; your JavaScript solve function returns data to the supplied driver.
Dart reference
import 'dart:convert';
import 'dart:io';
List<List<Object>> solve(List<dynamic> rows) {
final totals = <String, int>{};
for (final row in rows) {
final name = row[0] as String;
final quantity = row[1] as int;
totals[name] = (totals[name] ?? 0) + quantity;
}
final names = totals.keys.where((name) => totals[name]! > 0).toList()..sort();
return names.map((name) => <Object>[name, totals[name]!]).toList();
}
void main() {
final input = stdin.readLineSync()!;
print(jsonEncode(solve(jsonDecode(input) as List<dynamic>)));
}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 Dart Developers
1From Dart to JavaScript
Run JavaScriptStrings and TemplatesBindings and Block ScopeNumbers and ConversionNull and UndefinedRecap: Receipt4Iteration Pipelines
While and Early ExitMap and FilterReduce with an Initial ValueSorting Without SurprisesRecap: Build a Ranking2Decisions and Flow
Strict EqualityTruth TestsBranches and TernariesLoop Values and IndexesRecap: Shipping Rules5Functions
Functions and ReturnsDefaults and OptionsRest and Spread CallsClosures and CallbacksRecap: Pricing Function8Composition and Dispatch
CompositionInheritance and SuperDuck TypingValue Equality by ContractRecap: Channel Routing3Collections
Arrays and MutationObjects as RecordsMap and SetCopies and DestructuringRecap: Inventory Counts6Errors and Modules
JSON and Input BoundariesThrow and CatchES Modules and ImportsValidate Runtime ValuesRecap: Validate a Batch9Project: Order Processor
Model an OrderApply Member PricingPractice on your own: Online JavaScript compiler