Untitled

mail@pastecode.io avatar
unknown
kotlin
a month ago
2.9 kB
3
Indexable
Never
fun patchMermaid(input: String): String {
    if (!areBracketsBalanced(input)) {
        return input
    }

    val output = StringBuilder()
    val bracketPairs = mapOf('(' to ')', '[' to ']', '{' to '}')
    var i = 0
    while (i < input.length) {
        val char = input[i]
        if (char in bracketPairs.keys) {
            val openingBracket = char
            val closingBracket = bracketPairs[openingBracket]!!
            val endIndex = findMatchingBracket(input, i, openingBracket, closingBracket)
            if (endIndex != -1) {
                val content = input.substring(i + 1, endIndex)
                val processedContent = processLabelContent(content)
                output.append(openingBracket)
                output.append(processedContent)
                output.append(closingBracket)
                i = endIndex + 1
            } else {
                // Brackets are unmatched, return input as is
                return input
            }
        } else {
            output.append(char)
            i += 1
        }
    }
    return output.toString()
}

fun areBracketsBalanced(input: String): Boolean {
    val bracketPairs = mapOf('(' to ')', '[' to ']', '{' to '}')
    val stack = mutableListOf<Char>()

    for (char in input) {
        if (char in bracketPairs.keys) {
            stack.add(char)
        } else if (char in bracketPairs.values) {
            if (stack.isEmpty()) {
                return false
            }
            val lastOpenBracket = stack.removeAt(stack.size - 1)
            if (bracketPairs[lastOpenBracket] != char) {
                return false
            }
        }
    }
    return stack.isEmpty()
}

fun findMatchingBracket(
    input: String,
    startIndex: Int,
    openingBracket: Char,
    closingBracket: Char
): Int {
    var depth = 1
    var i = startIndex + 1
    while (i < input.length) {
        val char = input[i]
        if (char == openingBracket) {
            depth += 1
        } else if (char == closingBracket) {
            depth -= 1
            if (depth == 0) {
                return i
            }
        }
        i += 1
    }
    // If depth is not zero, brackets are unmatched
    return -1
}

fun processLabelContent(content: String): String {
    var newContent = content.trim()

    // Unescape any escaped quotes
    newContent = newContent.replace("\\\"", "\"")

    // Remove outer quotes if they are matching
    if (newContent.length >= 2 && (
            (newContent.startsWith("\"") && newContent.endsWith("\"")) ||
            (newContent.startsWith("'") && newContent.endsWith("'"))
        )) {
        newContent = newContent.substring(1, newContent.length - 1)
    }

    // Replace inner double quotes with single quotes
    newContent = newContent.replace("\"", "'")

    // Wrap content with double quotes
    newContent = "\"$newContent\""

    return newContent
}
Leave a Comment