All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.mythicdrops.PrettyPrint.kt Maven / Gradle / Ivy

There is a newer version: 9.0.4
Show newest version
package dev.mythicdrops

internal const val DEFAULT_PRETTY_PRINT_INDENT_WIDTH = 4

internal fun Any.prettyPrint(indentWidth: Int = DEFAULT_PRETTY_PRINT_INDENT_WIDTH): String {
    var indentLevel = 0

    fun padding() = "".padStart(indentLevel * indentWidth)

    val toString = toString()

    val stringBuilder = StringBuilder(toString.length)

    var i = 0
    while (i < toString.length) {
        when (val char = toString[i]) {
            '(', '[', '{' -> {
                indentLevel++
                stringBuilder.appendLine(char).append(padding())
            }
            ')', ']', '}' -> {
                indentLevel--
                stringBuilder.appendLine().append(padding()).append(char)
            }
            ',' -> {
                stringBuilder.appendLine(char).append(padding())
                // ignore space after comma as we have added a newline
                val nextChar = toString.getOrElse(i + 1) { char }
                if (nextChar == ' ') i++
            }
            else -> {
                stringBuilder.append(char)
            }
        }
        i++
    }

    return stringBuilder.toString()
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy