Created
July 29, 2019 15:34
-
-
Save latant/2200105e701f18015b49f43e75bd4d21 to your computer and use it in GitHub Desktop.
A function for string templating
This file contains hidden or 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
fun replaceParams(string: String, params: Map<String, Any>) = buildString { | |
var i = 0 | |
var j: Int | |
while (i < string.length) { | |
while (string[i] != '{') { | |
append(string[i]) | |
i++ | |
if (i > string.length) | |
return@buildString | |
} | |
if (i == string.lastIndex) | |
return@buildString | |
j = i + 1 | |
while (string[j] != '}') { | |
j++ | |
if (i > string.length) | |
return@buildString | |
} | |
val paramName = string.substring((i + 1), j) | |
val paramValue = params[paramName] | |
if (paramValue != null) { | |
append(paramValue) | |
} else { | |
while (i <= j) { | |
append(string[i]) | |
i++ | |
} | |
} | |
i = j + 1 | |
} | |
} | |
fun String.withParams(vararg params: Pair<String, Any>) = replaceParams(this, mapOf(*params)) | |
fun main() { | |
val template = "{greeting}, {name}, you are {property}" | |
println(template.withParams("greeting" to "Hello", "name" to "Mark", "property" to "tall")) | |
println(template.withParams("name" to "Manó")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment