Menu
CoddyTech

Port a Dart Ledger

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

challenge icon

Challenge

Easy

Port 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

Practice on your own: Online JavaScript compiler