Created
June 15, 2011 12:48
-
-
Save xlson/1027008 to your computer and use it in GitHub Desktop.
Adds method that will batch the values in a list into a new list containing batches of items
This file contains hidden or 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
Object.metaClass.partition = { partitionSize -> | |
def result = delegate.inject([[]]) { partitioned, it -> | |
if(partitioned.last().size() == partitionSize) { | |
partitioned << [it] | |
} else { | |
partitioned.last() << it | |
} | |
partitioned | |
} | |
result?.last().size() == 0 ? [] : result | |
} | |
assert [1, 2, 3, 4, 5].partition(1) == [[1], [2], [3], [4], [5]] | |
assert [1, 2, 3].partition(2) == [[1, 2], [3]] | |
assert [1, 2, 3].partition(5) == [[1, 2, 3]] | |
assert [].partition(100) == [] |
Nice, I hadn't even thought of that. My use case is for creating batches of data to be sent into a remote service. Partition that was used on the stackoverflow page is probably a name that is more in line with what it actually does.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like that this gives you an easy to read way to map a list, ie;