Menu
CoddyTech

迁移 Kotlin 账本

Coddy 面向 Kotlin 开发者的 JavaScript 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

将附带的 Kotlin 账本参考实现移植到 JavaScript。输入是一个由 [name, quantity] 对组成的 JSON 数组。名称只包含 ASCII 字符;数量是整数,所有计算出的总数都在 JavaScript 安全整数范围内。按名称累加每次更新,并保留中间的负数总数。汇总后,只保留正数总数,按 ASCII 顺序对名称排序,并返回 [name, total] 对。使用 Map,这样 __proto__ 这样的名称仍会被当作普通数据。不要在汇总前筛选更新。

在 exercise.js 中实现 solve 导出函数。锁定的 driver.js 会解析标准输入,并将返回的数据序列化为 JSON,末尾附带换行符。不要输出诊断信息。下面的完整源码参考有自己的 stdin 入口;你的 JavaScript solve 函数应将数据返回给提供的驱动程序。

Kotlin 参考实现

// JSON input is restricted to an array of [ASCII name, integer quantity] pairs.
// Numeric tokens may use decimal or exponent notation when their value is integral.
class LedgerInput(private val text: String) {
    private var position = 0
    private fun whitespace() {
        while (position < text.length && text[position].isWhitespace()) position++
    }
    private fun take(character: Char) {
        whitespace()
        require(position < text.length && text[position] == character)
        position++
    }
    private fun has(character: Char): Boolean {
        whitespace()
        return position < text.length && text[position] == character
    }
    private fun string(): String {
        take('"')
        val out = StringBuilder()
        while (true) {
            val character = text[position++]
            if (character == '"') return out.toString()
            if (character != '\\') {
                out.append(character)
            } else {
                when (val escape = text[position++]) {
                    '"', '\\', '/' -> out.append(escape)
                    'b' -> out.append('\b')
                    'f' -> out.append('\u000C')
                    'n' -> out.append('\n')
                    'r' -> out.append('\r')
                    't' -> out.append('\t')
                    'u' -> {
                        out.append(text.substring(position, position + 4).toInt(16).toChar())
                        position += 4
                    }
                    else -> error("Invalid JSON escape")
                }
            }
        }
    }
    private fun integer(): Long {
        whitespace()
        val start = position
        while (position < text.length && text[position] !in ",] \t\r\n") position++
        return java.math.BigDecimal(text.substring(start, position)).longValueExact()
    }
    fun rows(): List<Pair<String, Long>> {
        val result = mutableListOf<Pair<String, Long>>()
        take('[')
        if (!has(']')) {
            while (true) {
                take('[')
                val name = string()
                take(',')
                val quantity = integer()
                take(']')
                result.add(name to quantity)
                if (!has(',')) break
                take(',')
            }
        }
        take(']')
        whitespace()
        require(position == text.length)
        return result
    }
}
fun quoteJson(value: String): String = buildString {
    append('"')
    for (character in value) {
        when (character) {
            '"' -> append("\\\"")
            '\\' -> append("\\\\")
            '\b' -> append("\\b")
            '\u000C' -> append("\\f")
            '\n' -> append("\\n")
            '\r' -> append("\\r")
            '\t' -> append("\\t")
            else -> if (character < ' ') {
                append("\\u" + character.code.toString(16).padStart(4, '0'))
            } else append(character)
        }
    }
    append('"')
}
fun solve(rows: List<Pair<String, Long>>): List<Pair<String, Long>> {
    val totals = mutableMapOf<String, Long>()
    for ((name, quantity) in rows) totals[name] = (totals[name] ?: 0L) + quantity
    return totals.keys.filter { totals.getValue(it) > 0L }.sorted().map { it to totals.getValue(it) }
}
fun main() {
    val rows = LedgerInput(readLine()!!).rows()
    val result = solve(rows).joinToString(separator=",", prefix="[", postfix="]") {
        (name, total) -> "[" + quoteJson(name) + "," + total + "]"
    }
    println(result)
}

亲手试试

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)));

面向 Kotlin 开发者的 JavaScript中的所有课

自己练习: JavaScript 在线编译器