From afd6847ef3cf9aee357e6c23fc2f665413fa01d1 Mon Sep 17 00:00:00 2001 From: Max Howell Date: Fri, 7 Mar 2014 18:17:17 -0600 Subject: [PATCH] NSArray.chunk() --- NSArray+YOLO.m | 10 ++++++++++ README.markdown | 9 +++++++++ YOLO.h | 1 + tests | 6 ++++++ 4 files changed, 26 insertions(+) diff --git a/NSArray+YOLO.m b/NSArray+YOLO.m index 4161bf9..00bb2d3 100644 --- a/NSArray+YOLO.m +++ b/NSArray+YOLO.m @@ -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)) { diff --git a/README.markdown b/README.markdown index 3a9d1aa..ab9ff38 100644 --- a/README.markdown +++ b/README.markdown @@ -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){ diff --git a/YOLO.h b/YOLO.h index 2af2ae6..04c15eb 100644 --- a/YOLO.h +++ b/YOLO.h @@ -47,6 +47,7 @@ @end @interface NSArray (YOLO) +- (NSArray *(^)(NSUInteger))chunk; - (BOOL)empty; - (BOOL (^)(id o))has; - (NSArray *(^)(id (^)(id o)))pmap; diff --git a/tests b/tests index 10fd409..3422b74 100755 --- a/tests +++ b/tests @@ -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;