Skip to content

Commit

Permalink
NSArray.partition()
Browse files Browse the repository at this point in the history
  • Loading branch information
mxcl committed Mar 8, 2014
1 parent c77555b commit 2768aea
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions NSArray+Underscore.m
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@

@implementation NSArray (Underscore)

- (NSArray *(^)(id o))partition {
return ^NSArray *(BOOL(^block)(id o)) {
id aa = [NSMutableArray new];
id bb = [NSMutableArray new];
for (id o in self)
[block(o) ? aa : bb addObject:o];
return @[aa, bb];
};
}

- (NSArray *(^)(NSString *))pluck {
return ^NSArray *(NSString *key) {
if (!key.length)
Expand Down
11 changes: 11 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,17 @@ code.

`has` was chosen over `contains` or `includes` because it is short and clear.

###NSArray.partition()
```objc
id rv = @[@"A", @"B", @"AA"].partition(^(NSString *s){
return [s hasPrefix:@"A"];
});
//rv => @[@[@"A", @"AA"], @[@"B"]]
```

Partitions an array into two arrays based on the boolean return value of your
block.

###NSDictionary.map()
```objc
id rv = @{@1: @2, @2: @4, @3: @9}.map(^(id key, id obj){
Expand Down
1 change: 1 addition & 0 deletions YOLO.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
@end

@interface NSArray (Underscore)
- (NSArray *(^)(id blockReturningBool))partition;
- (NSArray *(^)(NSString *keypath))pluck;
- (NSArray *(^)(id arrayOrSetOrObject))without;
@end
Expand Down
14 changes: 14 additions & 0 deletions tests
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,20 @@ int main() {
STAssertEqualObjects(aa, bb, @"");
}
- (void)testPartition {
id aa = @[@1, @2, @3, @4].partition(^(NSNumber *n){
return n.intValue % 2 == 0;
});
id bb = @[@[@2, @4], @[@1, @3]];
STAssertEqualObjects(aa, bb, @"");
aa = @[@"A", @"B", @"AA"].partition(^(NSString *s){
return [s hasPrefix:@"A"];
});
bb = @[@[@"A", @"AA"], @[@"B"]];
STAssertEqualObjects(aa, bb, @"");
}
@end
Expand Down

0 comments on commit 2768aea

Please sign in to comment.