Menu
CoddyTech

Kotlin 장부 포팅하기

Coddy의 Kotlin 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

쉬움

함께 제공된 Kotlin 원장 참조 코드를 JavaScript로 포팅하세요. 입력은 [name, quantity] 쌍으로 이루어진 JSON 배열 하나입니다. 이름에는 ASCII 문자만 포함되며, 수량은 정수이고 계산된 모든 합계는 JavaScript의 안전한 정수 범위 내에 있습니다. 이름별로 모든 업데이트를 합산하고, 중간 합계가 음수여도 유지하세요. 집계한 후에는 양수인 합계만 남기고, 이름을 ASCII 순서로 정렬한 다음 [name, total] 쌍을 반환하세요. __proto__와 같은 이름도 일반 데이터로 처리되도록 Map을 사용하세요. 집계하기 전에 업데이트를 필터링하지 마세요.

exercise.js에서 solve 내보내기 함수를 구현하세요. 잠겨 있는 driver.js는 표준 입력을 파싱하고 반환된 데이터를 JSON으로 직렬화한 뒤 마지막에 줄바꿈 문자를 출력합니다. 진단 메시지는 출력하지 마세요. 아래의 전체 소스 참조 코드에는 자체 표준 입력 진입점이 있습니다. 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 컴파일러