Created
October 25, 2018 07:59
-
-
Save fbaierl/ade57727698a23b709d55441d7b9dfd3 to your computer and use it in GitHub Desktop.
Scala.js string interpolation like java.text.MessageFormat
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
object Format { | |
/** | |
* String interpolation [[java.text.MessageFormat]] style: | |
* {{{ | |
* format("{1} {0}", "world", "hello") // result: "hello world" | |
* format("{0} + {1} = {2}", 1, 2, "three") // result: "1 + 2 = three" | |
* format("{0} + {0} = {0}", 0) // throws MissingFormatArgumentException | |
* }}} | |
* @return | |
*/ | |
def format (text: String, args: Any*): String = { | |
var scalaStyled = text | |
val pattern = """{\d+}""".r | |
pattern.findAllIn(text).matchData foreach { | |
m => val singleMatch = m.group(0) | |
var number = singleMatch.substring(1, singleMatch.length - 1).toInt | |
// %0$s is not allowed so we add +1 to all numbers | |
number = 1 + number | |
scalaStyled = scalaStyled.replace(singleMatch, "%" + number + "$s") | |
} | |
scalaStyled.format(args:_*) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment