Skip to content

Instantly share code, notes, and snippets.

@cspickert
Last active August 29, 2015 13:57
Show Gist options
  • Save cspickert/9348928 to your computer and use it in GitHub Desktop.
Save cspickert/9348928 to your computer and use it in GitHub Desktop.
/**
To build (after building ReactiveCocoa):
$ clang -framework Foundation \
-framework AppKit \
-I./ReactiveCocoa/ReactiveCocoaFramework/build/Release/include/ReactiveCocoa-Mac \
-L./ReactiveCocoa/ReactiveCocoaFramework/build/Release \
-lReactiveCocoa-Mac \
-ObjC \
-g -o main chunks.m
*/
#import <Foundation/Foundation.h>
#import "RACSequence.h"
#import "NSArray+RACSequenceAdditions.h"
@interface RACSequence (Chunk)
- (RACSequence *)recursiveChunk:(NSInteger)size;
- (RACSequence *)iterativeChunk:(NSInteger)size;
@end
@implementation RACSequence (Chunk)
- (RACSequence *)recursiveChunk:(NSInteger)size
{
if (size <= 0 || [self head] == nil) {
return [RACSequence empty];
}
RACSequence *chunk = [self take:size];
RACSequence *rest = [self skip:size];
return [RACSequence sequenceWithHeadBlock:^id {
return chunk;
} tailBlock:^RACSequence *{
return [rest recursiveChunk:size];
}];
}
- (RACSequence *)iterativeChunk:(NSInteger)size
{
if (size <= 0 || [self head] == nil) {
return [RACSequence empty];
}
NSArray *array = [self array];
NSMutableArray *allChunks = [NSMutableArray arrayWithCapacity:[array count] / size + 1];
NSMutableArray *chunk = nil;
NSInteger count = 0;
for (id obj in array) {
if (chunk != nil && count >= size) {
[allChunks addObject:[chunk rac_sequence]];
count = 0;
chunk = nil;
}
if (chunk == nil) {
chunk = [NSMutableArray arrayWithCapacity:size];
}
[chunk addObject:obj];
count++;
}
if (chunk) {
[allChunks addObject:[chunk rac_sequence]];
}
return [allChunks rac_sequence];
}
@end
int main (int argc, char *argv[])
{
BOOL recursive = NO;
switch (argv[1][0]) {
case 'r':
recursive = YES;
break;
case 'i':
recursive = NO;
break;
default:
fprintf(stderr, "Specify 'i' for iterative or 'r' for recursive.\n");
return 1;
}
NSInteger const count = atoi(argv[2]);
NSInteger const chunkSize = atoi(argv[3]);
@autoreleasepool {
NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:count];
for (NSInteger i = 0; i < count; i++) {
[numbers addObject:@(i)];
}
RACSequence *sequence = [numbers rac_sequence];
RACSequence *chunkedSequence;
if (recursive) {
chunkedSequence = [sequence recursiveChunk:chunkSize];
} else {
chunkedSequence = [sequence iterativeChunk:chunkSize];
}
// Evaluate the sequence by converting it to an array of arrays
NSArray *chunkedArrays = [chunkedSequence valueForKeyPath:@"array.array"];
NSLog(@"Number of chunks: %li", [chunkedArrays count]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment