Skip to content

Instantly share code, notes, and snippets.

@dexterous
Last active April 19, 2021 07:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dexterous/2043690 to your computer and use it in GitHub Desktop.
Save dexterous/2043690 to your computer and use it in GitHub Desktop.
collectWithIndex in the cheap
@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"))
}
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