Skip to content

Instantly share code, notes, and snippets.

@mikelikespie
Created February 3, 2011 17:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikelikespie/809861 to your computer and use it in GitHub Desktop.
Save mikelikespie/809861 to your computer and use it in GitHub Desktop.
@interface NSArray (EnumerableExtras)
/**
* similar to a map
*/
- (NSArray *) objectsTransformedByBlock:(id (^)(id obj, NSUInteger idx, BOOL *stop))block;
/**
* filter the array
*/
- (NSArray *) objectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate;
/**
* takes the return value of the block as the key and maps it to the object for it
*/
- (NSDictionary *) dictionaryOfObjectsWithKeyBlock:(id (^)(id obj, NSUInteger idx, BOOL *stop))block;
@end
#import "NSArray+enumerableExtras.h"
@implementation NSArray (EnumerableExtras)
- (NSArray *) objectsTransformedByBlock:(id (^)(id obj, NSUInteger idx, BOOL *stop))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 obj, NSUInteger idx, BOOL *stop))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
@interface NSSet (EnumerableExtras)
/**
* set difference. self - other
*/
-(NSSet *) setByRemovingObjectsInSet:(NSSet *)other;
/**
* set difference. self - other
*/
-(NSSet *) setByRemovingObjectsInArray:(NSArray *)other;
/**
* set intersection
*/
-(NSSet *) setByKeepingObjectsInSet:(NSSet *)other;
/**
* set intersection
*/
-(NSSet *) setByKeepingObjectsInArray:(NSArray *)other;
@end
#import "NSSet+enumerableExtras.h"
@implementation NSSet (EnumerableExtras)
-(NSSet *) setByRemovingObjectsInSet:(NSSet *)other {
return [self objectsPassingTest:^(id obj, BOOL *stop) {
return (BOOL)![other containsObject:obj];
}];
}
-(NSSet *) setByRemovingObjectsInArray:(NSArray *)other {
return [self setByRemovingObjectsInSet:[NSSet setWithArray:other]];
}
-(NSSet *) setByKeepingObjectsInSet:(NSSet *)other {
return [self objectsPassingTest:^(id obj, BOOL *stop) {
return (BOOL)[other containsObject:obj];
}];
}
-(NSSet *) setByKeepingObjectsInArray:(NSArray *)other {
return [NSSet setWithArray:[other objectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [self containsObject:obj];
}]];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment