Skip to content

Instantly share code, notes, and snippets.

@stigi
Created August 9, 2011 15:48
Show Gist options
  • Select an option

  • Save stigi/1134408 to your computer and use it in GitHub Desktop.

Select an option

Save stigi/1134408 to your computer and use it in GitHub Desktop.
NSArray map reduce
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