Skip to content

Commit

Permalink
feat: Placeholder parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
BSpoones committed Jul 27, 2024
1 parent d4bb194 commit fc6dbb9
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.bspoones.zeus.util.text

@JvmName("NullStringParse")
fun String?.parse(vararg placeholders: Any): String? {
if (this == null) return null
return PlaceholderParser.parse(this,*placeholders)
}

@JvmName("StringParse")
fun String.parse(vararg placeholders: Any): String = PlaceholderParser.parse(this, *placeholders)

fun parse(input: String, vararg placeholders: Any) = PlaceholderParser.parse(input , *placeholders)

object PlaceholderParser {

private val SURROUNDING_CHARS = "<" to ">"

fun parse(text: String, vararg placeholders: Any): String {
if (placeholders.isEmpty()) return text
assert(placeholders.size % 2 == 0) { "Placeholders must be in a key-value pair!" }

var output = text

placeholders.toList().zipWithNext().forEach { (key, value) ->
assert(key is String) { "Placeholder key must be a string!" }
output = output.replace("${SURROUNDING_CHARS.first}$key${SURROUNDING_CHARS.second}", value.toString())
}
return output
}
}

0 comments on commit fc6dbb9

Please sign in to comment.