Monday, May 16, 2011

regex pattern "matches" ==~ with metaclass

Closure foundIn = { a, b ->
  print (/$a --> ${b}?? /); 
  return (a ==~ /${b}/); 
}
 
String testConditionRegex = "[abc]"

println foundIn('a', testConditionRegex) //true
println foundIn('z', testConditionRegex) //false
println foundIn(1, testConditionRegex) //false
 
println foundIn(2, 2) //true
println foundIn(12, 12.0) //false
println foundIn(null, testConditionRegex) //false
 
Object.metaClass.foundIn = { return foundIn (delegate, it); }
 
println ("4".foundIn("[1-9]")) //true
println (8.foundIn("[1-9]")) //true
println ((-8).foundIn("[1-9]")) //false

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

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