Last active
May 25, 2022 12:41
-
-
Save turboBasic/8b4bafd048953b15a6b3994881e0b2de to your computer and use it in GitHub Desktop.
Groovy: wrap variable number of nested Closure calls #groovy
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 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