Menu
CoddyTech

Adapta un libro mayor en Kotlin

Lección 47 de 48 del curso JavaScript para desarrolladores de Kotlin de Coddy.

challenge icon

Desafío

Fácil

Adapta a JavaScript la referencia del libro mayor adjunta, escrita en Kotlin. La entrada es una matriz JSON de pares [name, quantity]. Los nombres contienen solo caracteres ASCII; las cantidades son enteros y todos los totales calculados se mantienen dentro del rango de enteros seguros de JavaScript. Suma cada actualización por nombre, conservando los totales intermedios negativos. Después de la agregación, conserva solo los totales positivos, ordena los nombres según el orden ASCII y devuelve pares [name, total]. Usa un Map para que nombres como __proto__ sigan siendo datos comunes. No filtres las actualizaciones antes de agregarlas.

Implementa la exportación solve en exercise.js. El driver.js bloqueado analiza la entrada estándar y serializa los datos devueltos como JSON con un salto de línea final. No imprimas mensajes de diagnóstico. La referencia completa del código fuente que aparece abajo tiene su propio punto de entrada de stdin; tu función solve de JavaScript devuelve los datos al controlador proporcionado.

Referencia de 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)
}

Pruébalo tú mismo

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Llega un valor JSON por stdin. Devuelve datos; no imprimas nada dentro de solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Todas las lecciones de JavaScript para desarrolladores de Kotlin

Practica por tu cuenta: Compilador de JavaScript online