Skip to content

Instantly share code, notes, and snippets.

@turboBasic
Last active May 25, 2022 12:41
Show Gist options
  • Save turboBasic/8b4bafd048953b15a6b3994881e0b2de to your computer and use it in GitHub Desktop.
Save turboBasic/8b4bafd048953b15a6b3994881e0b2de to your computer and use it in GitHub Desktop.
Groovy: wrap variable number of nested Closure calls #groovy
/**
* Class Wrapper allows to wrap and execute variable number of nested Closures.
* Immediately-wrapped closure is accessible inside the wrapper as variable `_`.
*/
final class Wrapper {
private final List stack = []
Wrapper leftShift(Closure c) {
c.resolveStrategy = Closure.DELEGATE_FIRST
stack << c
return this
}
void unroll() {
_unroll stack
}
private void _unroll(List x) {
if (!x) {
return
}
def current = x.last()
current.delegate = [
_: x.size() == 1
? {}
: { _unroll x.init() }
]
current.call()
}
}
(new Wrapper() <<
{ println 'abc' } <<
{ for (i in 1..3) {
_.call()
}
} <<
{ for (i in 1..2) {
print 'ghi '
_.call()
}
}
).unroll()​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment