Created
August 9, 2011 15:48
-
-
Save stigi/1134408 to your computer and use it in GitHub Desktop.
NSArray map reduce
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
| typedef id(^mapFunction)(id obj); | |
| typedef id(^reduceFunction)(id obj1, id obj2); | |
| @implementation NSArray (NSArray_MapReduce) | |
| - (id)map:(mapFunction)mapFunction reduce:(reduceFunction)reduceFunction; | |
| { | |
| dispatch_queue_t reduceQueue = dispatch_queue_create(0, 0); | |
| dispatch_group_t group = dispatch_group_create(); | |
| __block id result = nil; | |
| dispatch_apply([self count], dispatch_get_current_queue(), ^(size_t i){ | |
| id obj = [self objectAtIndex:i]; | |
| id newObj = mapFunction(obj); | |
| dispatch_group_async(group, reduceQueue, ^(){ | |
| result = reduceFunction(result, newObj); | |
| }); | |
| }); | |
| dispatch_group_wait(group, DISPATCH_TIME_FOREVER); | |
| return result; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment