Ver Fonte

Better taboo checking

Thomas Dy há 11 anos atrás
pai
commit
b28ca46413
2 ficheiros alterados com 14 adições e 5 exclusões
  1. 5 4
      app/models/Card.scala
  2. 9 1
      test/ApplicationSpec.scala

+ 5 - 4
app/models/Card.scala

@@ -59,14 +59,15 @@ object Card {
 
 case class Card(word: String, taboo: Set[String]) {
 
+  lazy val tabooRegex = (taboo + word).map { word =>
+    ("\\b"+word.toLowerCase+"\\b").r
+  }
+
   def isTaboo(text: String) = {
     val lower = text.toLowerCase
-    def contains(word: String) = {
-      lower.indexOf(word.toLowerCase) >= 0
-    }
 
     // check if text contains word or anything in taboo
-    (taboo + word).map(contains).foldLeft(false)(_ || _)
+    tabooRegex.map(!_.findFirstIn(lower).isEmpty).foldLeft(false)(_ || _)
   }
 
   def isCorrect(text: String) = {

+ 9 - 1
test/ApplicationSpec.scala

@@ -50,7 +50,15 @@ class ApplicationSpec extends Specification {
     "Check the entire message" in {
       card.isTaboo("The word is test") must beTrue
       card.isTaboo("I am not allowed to say") must beTrue
-      card.isTaboo("swords") must beTrue
+      card.isTaboo("*words*") must beTrue
+      card.isTaboo("these/not/allowed") must beTrue
+    }
+
+    "Don't check parts of words" in {
+      card.isTaboo("area") must beFalse
+      card.isTaboo("knots") must beFalse
+      card.isTaboo("care") must beFalse
+      card.isTaboo("swords") must beFalse
     }
 
   }