移植 Swift 账本
Coddy 面向 Swift 开发者的 JavaScript 课程的第 47 课,共 48 课。
挑战
简单根据下面完整的 Swift 参考代码进行移植。输入是一个由 [name, quantity] 对组成的 JSON 数组。名称仅包含 ASCII 字符,数量为整数。按名称汇总每次更新,然后只保留总数为正的项。按 ASCII 顺序对名称排序,并返回 [name, total] 对。使用 JavaScript Map,这样像 __proto__ 这样的名称仍会作为普通数据处理。所有输入数字和中间整数总数都在 JavaScript 安全整数范围内。
Swift 程序使用带默认值下标的类型化 Dictionary、Int64 累加、排序后的键和 compactMap。JavaScript 移植版本使用 Map 和 Number,数值均处于指定的安全范围内。与 Swift Dictionary 的迭代不同,JavaScript Map 会保留插入顺序,但本题明确要求按名称排序。Foundation 负责读取和写入这一个 JSON 值;JavaScript 驱动程序会为你处理这个边界。
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)!)编辑 exercise.js,并保留其导出的 solve(input) API。可见的锁定文件 driver.js 会读取 JSON,并将返回值作为紧凑 JSON 输出,末尾加一个换行符。不要添加诊断输出。
亲手试试
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// 从 stdin 接收一个 JSON 值。返回数据,不要在 solve 内打印。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
面向 Swift 开发者的 JavaScript中的所有课
自己练习: JavaScript 在线编译器