Menu
CoddyTech

Porter un registre Kotlin

Leçon 47 sur 48 du cours JavaScript pour les développeurs Kotlin de Coddy.

challenge icon

Défi

Facile

Transpose en JavaScript la référence Kotlin du registre fournie. L’entrée est un tableau JSON de paires [name, quantity]. Les noms ne contiennent que des caractères ASCII ; les quantités sont des entiers et tous les totaux calculés restent dans la plage des entiers sûrs de JavaScript. Additionne chaque mise à jour par nom, en conservant les totaux intermédiaires négatifs. Après l’agrégation, ne garde que les totaux positifs, trie les noms dans l’ordre ASCII et renvoie des paires [name, total]. Utilise une Map pour que les noms tels que __proto__ restent des données ordinaires. Ne filtre pas les mises à jour avant l’agrégation.

Implémente l’export solve dans exercise.js. Le fichier verrouillé driver.js analyse l’entrée standard et sérialise les données renvoyées en JSON, avec un saut de ligne final. N’affiche aucun diagnostic. La référence complète ci-dessous a son propre point d’entrée sur stdin ; ta fonction JavaScript solve renvoie les données au pilote fourni.

Référence 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)
}

Essayez vous-même

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Une valeur JSON arrive sur stdin. Renvoyez des données ; n’affichez rien dans solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Toutes les leçons de JavaScript pour les développeurs Kotlin

Entraînez-vous par vous-même : Compilateur JavaScript en ligne