-
-
Save timyates/b00be3058d86ccaa3612 to your computer and use it in GitHub Desktop.
Quick Match/When implementation
This file contains 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
class When { | |
def condition | |
def result | |
def getAt( List a ) { | |
condition = a | |
this | |
} | |
def call( result ) { | |
this.result = result | |
} | |
def propertyMissing( String result ) { | |
this.result = result | |
} | |
} | |
class Otherwise { | |
def result | |
Otherwise( result ) { | |
this.result = result | |
} | |
} | |
class Matcher { | |
def var | |
Closure closure | |
List<When> cases = [] | |
Otherwise otherwise | |
public Matcher( var, closure ) { | |
this.var = var | |
this.closure = closure | |
} | |
def propertyMissing( name ) { | |
def w = new When() | |
cases << w | |
w | |
} | |
def when( condition ) { | |
cases << new When( condition:condition ) | |
} | |
def when( condition, result ) { | |
cases << new When( condition:condition, result:result ) | |
} | |
def otherwise( result ) { | |
this.otherwise = new Otherwise( result ) | |
} | |
public match() { | |
closure.delegate = this | |
closure.resolveStrategy = Closure.DELEGATE_ONLY | |
closure() | |
cases.find { var == it.condition }?.result ?: otherwise?.result | |
} | |
} | |
def match( var, c ) { | |
new Matcher( var, c ).match() | |
} | |
def a = 'tim' | |
// No commas | |
println match( a ) { | |
when 'dave' 'Hi Dave' | |
when 'tim' 'Hi Tim' | |
otherwise 'none of the above' | |
} | |
// Commas | |
a = 'William' | |
println match( a ) { | |
when 'dave', 'Hi Dave' | |
when 'tim', 'Hi Tim' | |
otherwise 'none of the above' | |
} | |
// Lists (can't use commas) | |
a = [1,3] | |
println match( a ) { | |
when [1,2] 'One and two' | |
when [1,3] 'One and three' | |
when [2,1] 'Two and one' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment