Created
October 25, 2023 21:00
-
-
Save ianlintner/e4834a3475ccb969d32a2581e8e85c3e to your computer and use it in GitHub Desktop.
Scala Word case transformation (from json4s)
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
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), "_") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Link:
https://github.com/json4s/json4s/blob/3daa876d2fdbc117f80cb1dfd65e7112eb109948/ast/shared/src/main/scala/org/json4s/MonadicJValue.scala#L411