Skip to content

Instantly share code, notes, and snippets.

@ppazos
Last active September 13, 2016 23:09
Show Gist options
  • Save ppazos/38ce0bdb3159637f0a681b4ddd65efd7 to your computer and use it in GitHub Desktop.
Save ppazos/38ce0bdb3159637f0a681b4ddd65efd7 to your computer and use it in GitHub Desktop.
Externalize filters by using closures
/**
* We have two functions with exactly the same code, but one has a filter, so I want to use the same code
* but inject the filter by using a closure:
*/
// Filters
def filter_between = { min, max, n ->
return min < n && n < max
}
def filter_null = {
return true
}
// Function that uses the filter
boolean check( int n, Closure c )
{
// other code
if (c.call(n)) println "do something"
// more code
}
// Calls
println check(100, filter_null) // execute without filter
println check(100, filter_between.curry(10).curry(500)) // 100 between 10 and 1500
println check(1000, filter_between.curry(10).curry(500)) // 1000 between 10 and 1500
println check(4, filter_between.curry(10).curry(500)) // 4 between 10 and 1500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment