GroovyのList#takeメソッドが便利

2019-03-01Groovy

よく組むロジックだが、いつもしこしこコーディングしていた処理が組み込みメソッドで用意されてた。
とあるリストから、前方3件だけ取得したい。ただしリストが2件以下の場合はすべて返却。

#!/usr/bin/env groovy
def list = ["aaa", "bbb", "ccc", "ddd", "eee"]

def headEx(list, int n) {
    if (n-- > 0 && !list.empty) {
        return [list.head()] + headEx(list.tail(), n)
    } else {
        return []
    }
}

assert ["aaa", "bbb", "ccc", "ddd", "eee"] == headEx(list, 6)
assert ["aaa", "bbb", "ccc", "ddd", "eee"] == headEx(list, 5)
assert ["aaa", "bbb", "ccc"] == headEx(list, 3)
assert ["aaa", "bbb"] == headEx(list, 2)
assert ["aaa"] == headEx(list, 1)
assert [] == headEx(list, 0)
println "finish!"

List#take 使うと簡単に実現可能。

def list = ["aaa", "bbb", "ccc", "ddd", "eee"]
assert ["aaa", "bbb", "ccc", "ddd", "eee"] == list.take(6)
assert ["aaa", "bbb", "ccc", "ddd", "eee"] == list.take(5)
assert ["aaa", "bbb", "ccc"] == list.take(3)
assert ["aaa", "bbb"] == list.take(2)
assert ["aaa"] == list.take(1)
assert [] == list.take(0)
println "finish!"

2019-03-01Groovy