Wednesday, May 4, 2011

Until with metaclass and delegate

Object.metaClass.until = { cond, command = {it} ->
    delegate = delegate as List
    def result = []
    for (def i in delegate) {
        if (!cond(i)) { result << command(i) }
        else { break }
    }
    return result
}

def a = [1,2,3,4,5,6,8,1]
def b = [1.0,2d,3f,4.0,5f,6d,8d,1d]
def c = "123456781"
def d = true

println a.until({it == 6})
println a.until({it == 6}) { it + it }
println b.until({it == 6d}) { it + it }
println c.until({it == '6'}) { it + it }
println d.until({it == false}) { it }

see: http://groovyconsole.appspot.com/script/476001

No comments:

Post a Comment