-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
30 changes: 30 additions & 0 deletions
30
src/main/kotlin/org/bspoones/zeus/util/text/PlaceholderParser.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |