Skip to content

Instantly share code, notes, and snippets.

@ianlintner
Created October 25, 2023 21:00
Show Gist options
  • Save ianlintner/e4834a3475ccb969d32a2581e8e85c3e to your computer and use it in GitHub Desktop.
Save ianlintner/e4834a3475ccb969d32a2581e8e85c3e to your computer and use it in GitHub Desktop.
Scala Word case transformation (from json4s)
import java.util.Locale
/** Exposing privates from MonadicJValue
* https://github.com/json4s/json4s/blob/3daa876d2fdbc117f80cb1dfd65e7112eb109948/ast/shared/src/main/scala/org/json4s/MonadicJValue.scala#L411
*/
object CaseTransformer {
def camelize(word: String): String = {
if (word.nonEmpty) {
val w = pascalize(word)
w.substring(0, 1).toLowerCase(Locale.ENGLISH) + w.substring(1)
} else {
word
}
}
def pascalize(word: String): String = {
val lst = word.split("_").filterNot(_.isEmpty).toList
(lst.headOption.map(s => s.substring(0, 1).toUpperCase(Locale.ENGLISH) + s.substring(1)).get ::
lst.tail.map(s => s.substring(0, 1).toUpperCase + s.substring(1))).mkString("")
}
def underscoreCamelCasesOnly(word: String): String = {
val firstPattern = "([A-Z]+)([A-Z][a-z])".r
val secondPattern = "([a-z\\d])([A-Z])".r
val replacementPattern = "$1_$2"
secondPattern
.replaceAllIn(
firstPattern.replaceAllIn(word, replacementPattern),
replacementPattern
)
.toLowerCase
}
def underscore(word: String): String = {
val spacesPattern = "[-\\s]".r
spacesPattern.replaceAllIn(underscoreCamelCasesOnly(word), "_")
}
}