Last active
April 19, 2021 07:16
-
-
Save dexterous/2043690 to your computer and use it in GitHub Desktop.
collectWithIndex in the cheap
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
@Category(List) | |
class Enumerator { | |
def collectWithIndex(Closure closure) { | |
def index = 0 | |
this.collect { closure.call(it, index++) } | |
} | |
} | |
println 'iterating with indices using Object.eachWithIndex' | |
['foo', 'bar', 'boo', 'baz'].eachWithIndex { e, i -> | |
println "element[$i] == $e" | |
} | |
println '' | |
println 'collecting with indices using Enumerator.collectWithIndex' | |
use(Enumerator) { | |
println(['foo', 'bar', 'boo', 'baz']. | |
collectWithIndex { e, i -> "element[$i] == $e" }. | |
join("\n")) | |
} |
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
print '\n'.join( | |
'element[{0}] == {1}'.format(index, element) for | |
index, element in | |
enumerate(['foo', 'bar', 'boo', 'baz']) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment