dev.mythicdrops.PrettyPrint.kt Maven / Gradle / Ivy
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()
}