Created
February 7, 2018 09:28
-
-
Save petitviolet/6efd010e8838123d1492c9bb2c6a541e to your computer and use it in GitHub Desktop.
String converter for camelCase <-> snake_case
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
object StringFormatter { | |
private val spacesPattern = "[-\\s]".r | |
private val firstPattern = "([A-Z]+)([A-Z][a-z])".r | |
private val secondPattern = "([a-z\\d])([A-Z])".r | |
private val replacementPattern = "$1_$2" | |
implicit class stringFormatter(val word: String) extends AnyVal { | |
def snakenize: String = { | |
spacesPattern | |
.replaceAllIn(secondPattern.replaceAllIn( | |
firstPattern.replaceAllIn(word, replacementPattern), | |
replacementPattern | |
), | |
"_") | |
.toLowerCase | |
} | |
def camelize: String = { | |
@scala.annotation.tailrec | |
def loop(left: List[Char] = Nil, right: List[Char] = word.toList): List[Char] = | |
right match { | |
case '_' :: c :: rest => loop(c.toUpper :: left, rest) | |
case '_' :: Nil => left | |
case c :: rest => loop(c :: left, rest) | |
case Nil => left | |
} | |
loop().reverse.mkString | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
implemented as a library feature.
https://github.com/petitviolet/scala-operator/blob/master/modules/operator/src/main/scala/net/petitviolet/operator/StringOps.scala