From fc6dbb976a2431eeeee18172b31a11404e5786cd Mon Sep 17 00:00:00 2001 From: BSpoones <76079263+BSpoones@users.noreply.github.com> Date: Sat, 27 Jul 2024 01:20:46 +0100 Subject: [PATCH] feat: Placeholder parsing --- .../zeus/util/text/PlaceholderParser.kt | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt diff --git a/src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt b/src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt new file mode 100644 index 0000000..f8d99e1 --- /dev/null +++ b/src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt @@ -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 + } +} \ No newline at end of file