Skip to content

Instantly share code, notes, and snippets.

@snackycracky
Created June 24, 2011 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snackycracky/1044484 to your computer and use it in GitHub Desktop.
Save snackycracky/1044484 to your computer and use it in GitHub Desktop.
inject
public Object inject(Object initialValue, Closure closure)
Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as foldLeft in functional parlance. Examples:
assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val }
assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val }
assert 'The quick brown fox' ==
['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val }
assert 'bat' ==
['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min }
def max = { a, b -> [a, b].max() }
def animals = ['bat', 'rat', 'cat']
assert 'rat' == animals.inject('aaa', max)
Visual representation of the last example above:
initVal animals[0]
v v
max('aaa', 'bat') => 'bat' animals[1]
v v
max('bat', 'rat') => 'rat' animals[2]
v v
max('rat', 'cat') => 'rat'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment