diff --git a/UsefulBits/Foundation/NSArray+Blocks.h b/UsefulBits/Foundation/NSArray+Blocks.h index 6494e2e..c7cfe7a 100644 --- a/UsefulBits/Foundation/NSArray+Blocks.h +++ b/UsefulBits/Foundation/NSArray+Blocks.h @@ -45,6 +45,8 @@ - (NSArray *)map:(id (^)(id item))block; - (NSArray *)map:(id (^)(id item))block filterNil:(BOOL)filter_nil; +- (NSArray *)mapWithIndex:(id (^)(id item, NSUInteger index))block; +- (NSArray *)mapWithIndex:(id (^)(id item, NSUInteger index))block filterNil:(BOOL)filter_nil; - (id)reduce:(id (^)(id current, id item))block initial:(id)initial; - (NSArray *)intersperse:(id (^) (id current, id next))separator; diff --git a/UsefulBits/Foundation/NSArray+Blocks.m b/UsefulBits/Foundation/NSArray+Blocks.m index 77ddcb3..c301353 100644 --- a/UsefulBits/Foundation/NSArray+Blocks.m +++ b/UsefulBits/Foundation/NSArray+Blocks.m @@ -153,13 +153,26 @@ - (NSArray *)map:(id (^)(id item))block; } - (NSArray *)map:(id (^)(id item))block filterNil:(BOOL)filter_nil; +{ + return [self mapWithIndex:^id(id item, NSUInteger index) { + return block(item); + } filterNil:filter_nil]; +} + +- (NSArray *)mapWithIndex:(id (^)(id item, NSUInteger index))block; +{ + return [self mapWithIndex:block filterNil:YES]; +} + +- (NSArray *)mapWithIndex:(id (^)(id item, NSUInteger index))block filterNil:(BOOL)filter_nil; { NSMutableArray *result = [NSMutableArray arrayWithCapacity:[self count]]; - - for (id obj in self) + + for (NSUInteger idx = 0; idx < [self count]; idx++) { - id instance = block(obj); - + id obj = [self objectAtIndex:idx]; + id instance = block(obj, idx); + if (nil != instance) { [result addObject:instance]; @@ -169,7 +182,7 @@ - (NSArray *)map:(id (^)(id item))block filterNil:(BOOL)filter_nil; [result addObject:[NSNull null]]; } } - + return [NSArray arrayWithArray:result]; }