Menu
CoddyTech

Przenieś księgę rachunkową napisaną w Kotlinie

Lekcja 47 z 48 w kursie JavaScript dla programistów Kotlin w Coddy.

challenge icon

Wyzwanie

Łatwy

Przenieś do JavaScriptu towarzyszącą referencyjną implementację księgi w Kotlinie. Dane wejściowe to jedna tablica JSON zawierająca pary [name, quantity]. Nazwy zawierają wyłącznie znaki ASCII; ilości są liczbami całkowitymi, a wszystkie obliczone sumy mieszczą się w zakresie bezpiecznych liczb całkowitych JavaScriptu. Zsumuj wszystkie aktualizacje dla każdej nazwy, zachowując ujemne sumy pośrednie. Po agregacji pozostaw tylko dodatnie sumy, posortuj nazwy według kolejności ASCII i zwróć pary [name, total]. Użyj Map, aby nazwy takie jak __proto__ pozostały zwykłymi danymi. Nie filtruj aktualizacji przed agregacją.

Zaimplementuj eksport solve w pliku exercise.js. Zablokowany plik driver.js analizuje standardowe wejście i serializuje zwrócone dane jako JSON z końcowym znakiem nowej linii. Nie wypisuj komunikatów diagnostycznych. Poniższy kompletny kod referencyjny ma własny punkt wejścia odczytujący standardowe wejście; Twoja funkcja JavaScript solve zwraca dane do dostarczonego sterownika.

Implementacja referencyjna w Kotlinie

// 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)
}

Spróbuj swoich sił

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Na stdin trafia jedna wartość JSON. Zwróć dane; nie wypisuj nic wewnątrz solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Wszystkie lekcje w sekcji JavaScript dla programistów Kotlin

Poćwicz samodzielnie: Kompilator JavaScript online