Menu
CoddyTech

Chuyển sổ cái Kotlin sang nền tảng khác

Bài học 47 trên 48 trong khóa học JavaScript dành cho nhà phát triển Kotlin của Coddy.

challenge icon

Thử thách

Dễ

Chuyển bản tham chiếu sổ cái bằng Kotlin đi kèm sang JavaScript. Đầu vào là một mảng (array) JSON gồm các cặp [name, quantity]. Tên chỉ chứa ký tự ASCII; số lượng là số nguyên và mọi tổng được tính đều nằm trong phạm vi số nguyên an toàn của JavaScript. Cộng mọi lần cập nhật theo tên, giữ lại các tổng trung gian âm. Sau khi cộng gộp, chỉ giữ lại các tổng dương, sắp xếp tên theo thứ tự ASCII và trả về các cặp [name, total]. Dùng Map để những tên như __proto__ vẫn là dữ liệu thông thường. Không lọc các lần cập nhật trước khi cộng gộp.

Triển khai phần export solve trong exercise.js. driver.js bị khóa sẽ phân tích đầu vào tiêu chuẩn và chuyển dữ liệu trả về thành JSON, kèm một ký tự xuống dòng ở cuối. Không in thông tin chẩn đoán. Bản tham chiếu mã nguồn đầy đủ bên dưới có điểm vào stdin riêng; hàm solve bằng JavaScript của bạn trả dữ liệu cho driver được cung cấp.

Bản tham chiếu 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)
}

Tự làm thử

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Một giá trị JSON được gửi qua stdin. Trả về dữ liệu, đừng in ra trong solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Tất cả bài học trong JavaScript dành cho nhà phát triển Kotlin

Tự luyện tập: Trình biên dịch JavaScript online