Skip to content

Instantly share code, notes, and snippets.

@Pritesh-Patel
Last active February 27, 2016 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pritesh-Patel/9113c0f47af2fcaea2ce to your computer and use it in GitHub Desktop.
Save Pritesh-Patel/9113c0f47af2fcaea2ce to your computer and use it in GitHub Desktop.
A chat sanitiser exercise to get familiar with Kotlin
data class BadWord(val word:String, val severity:Int)
fun main(args: Array<String>) {
val chat = Chat()
while(true){
println("Enter message...")
val input = readLine()
if(input == "!q") System.exit(0)
chat.printWithWarning(input!!)
}
}
class Chat:Sanitiser {
override val badWords: Set<BadWord> =
setOf ( BadWord("hi", 2), BadWord("hello", 4),
BadWord("star", 1), BadWord("wars", 6),
BadWord("work",9), BadWord("iron",4))
fun printWithWarning(s:String){
val score = sanitiseScore(s, Level1Validation(), Level2Validation())
when(score) {
0 -> println(s)
in 1..4 -> println("Warning($score): Watch your language: $s")
in 4..7 -> println("Warning($score): Alerting moderator: $s")
else -> println("Action($score): Ban hammer!: $s")
}
}
}
interface Sanitiser {
val badWords:Set<BadWord>
fun Level1Validation() : (s:String) -> Int = { s ->
badWords.intersect(s.split(" ")).size
}
fun Level2Validation() : (s: String) -> Int = { s ->
val words = s.split(" ")
badWords.fold(0) { total, bw -> if (words.contains(bw.word)) total + bw.severity else total }
}
fun sanitiseScore(s: String, vararg sanitisers: (String) -> (Int)) =
sanitisers.fold(0) { total, f -> total + f(s) } / sanitisers.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment