Created
June 22, 2013 16:36
-
-
Save sortega/5841506 to your computer and use it in GitHub Desktop.
NameInverter in Scala by me
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
package cleancode | |
object NameInverter { | |
def apply(name: String): String = | |
swapFirstAndLast(splitName(name).dropWhile(isHonorific)).mkString(" ") | |
def swapFirstAndLast(parts: List[String]) = parts match { | |
case first :: last :: postNominals => last + "," :: first :: postNominals | |
case _ => parts | |
} | |
private def splitName(name: String) = name.trim().split("\\s+").toList | |
private def isHonorific(word: String) = word.matches("Mr\\.|Ms\\.") | |
} |
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
package cleancode | |
import org.scalatest.FlatSpec | |
import org.scalatest.matchers.MustMatchers | |
class NameInverterTest extends FlatSpec with MustMatchers { | |
"The name inverter" must "return empty string given an empty string" in { | |
NameInverter("") must be ("") | |
} | |
it must "return simple names as they are" in { | |
NameInverter("Name") must be ("Name") | |
} | |
it must "return remove extra spaces" in { | |
NameInverter(" Name ") must be ("Name") | |
} | |
it must "return last, first for full names" in { | |
NameInverter("First Last") must be ("Last, First") | |
} | |
it must "ignore honorifics" in { | |
NameInverter("Mr. First Last") must be("Last, First") | |
NameInverter("Ms. First Last") must be("Last, First") | |
} | |
it must "preserve post nominals at the end" in { | |
NameInverter("First Last Sr.") must be ("Last, First Sr.") | |
NameInverter("First Last BS. Phd.") must be ("Last, First BS. Phd.") | |
} | |
it must "do all the things above for the same name" in { | |
NameInverter(" Mr. Robert Martin III esq. ") must be ("Martin, Robert III esq.") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment