Menu
CoddyTech

Port a Swift Ledger

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

challenge icon

Challenge

Easy

Port the complete Swift reference below. Input is one JSON array of [name, quantity] pairs. Names contain only ASCII characters and quantities are integers. Sum every update by name, then retain only positive totals. Sort names by ASCII order and return [name, total] pairs. Use a JavaScript Map so names such as __proto__ remain ordinary data. All input numbers and intermediate integer totals stay within JavaScript's safe integer range.

The Swift program uses a typed Dictionary with a defaulted subscript, Int64 accumulation, sorted keys and compactMap. The JavaScript port uses Map and Number within the stated safe range. Unlike Swift Dictionary iteration, JavaScript Map preserves insertion order, but this report explicitly requires sorted names. Foundation reads and writes the one JSON value; the JavaScript driver supplies that boundary for you.

import Foundation
// Inputs and every intermediate total are within JavaScript's safe integer range.
func solve(_ rows: [[Any]]) -> [[Any]] {
    var totals: [String: Int64] = [:]
    for row in rows {
        let name = row[0] as! String
        let quantity = (row[1] as! NSNumber).int64Value
        totals[name, default: 0] += quantity
    }
    return totals.keys.sorted().compactMap { name -> [Any]? in
        let total = totals[name]!
        return total > 0 ? [name, total] : nil
    }
}
let input = FileHandle.standardInput.readDataToEndOfFile()
let rows = try! JSONSerialization.jsonObject(with: input) as! [[Any]]
let output = try! JSONSerialization.data(withJSONObject: solve(rows), options: [.withoutEscapingSlashes])
print(String(data: output, encoding: .utf8)!)

Edit exercise.js and keep its exported solve(input) API. The visible locked driver.js reads JSON and prints the return value as compact JSON followed by a newline. Do not add diagnostic output.

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 Swift Developers

Practice on your own: Online JavaScript compiler