Spock Web Console

subscribe to the feed Subscribe
abbrev(String) (via #spockwebconsole)
tweet this script Tweet

abbrev(String)

Published 1 year ago by slashdashpipe with tags string abbreviation
Actions  ➤ Edit In Console Back To Console Show/Hide Line Numbers View Recent Scripts
import spock.lang.*
class MyFirstSpec extends Specification {
  @Unroll
  def "ABBREV(#max) of [#str] is (#abbr)"() {
    expect:
     abbrev(str,max) == abbr
    where:
     str                     | abbr   | max
     null                    | ''     | null
     ""                      | ''     | null
     " 1"                    | '1'    | null
     "Bonjour"               | 'B'    | null
     "Bonjour Tout le monde" | 'BTLM' | null
     "Bonjour Tout le Monde" | 'BTLM' | null
     "Bonjour Tout le Monde" | 'BT'   | 2
  }

  static abbrev(str,max=null){
    def words = str?.split('(\\W+)').collect{
        it ? it[0].toUpperCase() : ''
    }.findAll{it}
    (max && max < words.size() 
        ? words[0..(max-1)] : 
            words).join('')
  }

}