Last active
          February 27, 2016 22:11 
        
      - 
      
- 
        Save Pritesh-Patel/9113c0f47af2fcaea2ce to your computer and use it in GitHub Desktop. 
    A chat sanitiser exercise to get familiar with Kotlin
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | 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