Skip to content

Instantly share code, notes, and snippets.

@mikelikespie
Created January 15, 2011 21:50
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 mikelikespie/781298 to your computer and use it in GitHub Desktop.
Save mikelikespie/781298 to your computer and use it in GitHub Desktop.
Some fun stuff for enumerating
@interface NSArray (EnumerableStuff)
/**
* similar to a map
*/
- (NSArray *) objectsTransformedByBlock:(id (^)(id, NSUInteger, BOOL *))block;
/**
* filter the array
*/
- (NSArray *) objectsPassingTest:(BOOL (^)(id, NSUInteger, BOOL *))predicate;
/**
* takes the return value of the block as the key and maps it to the object for it
*/
- (NSDictionary *) dictionaryOfObjectsWithKeyBlock:(id (^)(id, NSUInteger, BOOL *))block;
@end
#import "NSArray+enumerableStuff.h"
@implementation NSArray (EnumerableStuff)
- (NSArray *) objectsTransformedByBlock:(id (^)(id, NSUInteger, BOOL *))block {
NSMutableArray *ret = [NSMutableArray arrayWithCapacity:[self count]];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[ret addObject:block(obj, idx, stop)];
}];
return ret;
}
- (NSArray *) objectsPassingTest:(BOOL (^)(id, NSUInteger, BOOL *))predicate {
return [self objectsAtIndexes:[self indexesOfObjectsPassingTest:predicate]];
}
- (NSDictionary *) dictionaryOfObjectsWithKeyBlock:(id (^)(id, NSUInteger, BOOL *))block {
NSArray *keys = [self objectsTransformedByBlock:block];
return [NSDictionary dictionaryWithObjects:self forKeys:keys];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment