Skip to content

Commit

Permalink
NSArray.chunk()
Browse files Browse the repository at this point in the history
  • Loading branch information
mxcl committed Mar 8, 2014
1 parent 2768aea commit afd6847
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions NSArray+YOLO.m
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ - (NSSet *)set {
return [NSSet setWithArray:self];
}

- (NSArray *(^)(NSUInteger))chunk {
return ^(NSUInteger size){
id aa = [NSMutableArray new];
const int n = self.count / size;
for (int x = 0; x < n; ++x)
[aa addObject:self.slice(x*size, size)];
return aa;
};
}

- (NSArray *(^)(id (^)(id o)))pmap {
return ^NSArray *(id (^block)(id))
{
Expand Down
9 changes: 9 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,15 @@ code.

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

###NSArray.chunk()
```objc
id rv = @[@1, @2, @3, @4].chunk(2)

// rv => @[@[@1, @2], @[@3, @4]]
```

Chunks your array into an array of chunk-size arrays.

###NSArray.partition()
```objc
id rv = @[@"A", @"B", @"AA"].partition(^(NSString *s){
Expand Down
1 change: 1 addition & 0 deletions YOLO.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
@end

@interface NSArray (YOLO)
- (NSArray *(^)(NSUInteger))chunk;
- (BOOL)empty;
- (BOOL (^)(id o))has;
- (NSArray *(^)(id (^)(id o)))pmap;
Expand Down
6 changes: 6 additions & 0 deletions tests
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,12 @@ int main() {
STAssertEqualObjects(aa, bb, @"");
}
- (void)testChunk {
id aa = @[@1, @2, @3, @4].chunk(2);
id bb = @[@[@1, @2], @[@3, @4]];
STAssertEqualObjects(aa, bb, @"");
}
- (void)testPartition {
id aa = @[@1, @2, @3, @4].partition(^(NSNumber *n){
return n.intValue % 2 == 0;
Expand Down

0 comments on commit afd6847

Please sign in to comment.