Last active
December 20, 2015 13:39
-
-
Save jparishy/6140873 to your computer and use it in GitHub Desktop.
Today in Ugly Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.m | |
// Zip | |
// | |
// Created by Julius Parishy on 8/2/13. | |
// Copyright (c) 2013 Fitocracy. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
#include <stdarg.h> | |
NSArray *zip(id(^map)(NSArray *objs), int count, NSArray *first, ...) | |
{ | |
va_list ap; | |
va_start(ap, first); | |
NSMutableArray *allArrays = [NSMutableArray array]; | |
[allArrays addObject:first]; | |
for(int i = 0; i < count - 1; ++i) | |
{ | |
[allArrays addObject:va_arg(ap, NSArray *)]; | |
} | |
NSArray *arrays = [allArrays sortedArrayUsingComparator:^NSComparisonResult(NSArray *array1, NSArray *array2) { | |
return [@(array1.count) compare:@(array2.count)]; | |
}]; | |
NSMutableArray *zipped = [NSMutableArray array]; | |
NSInteger iterationCount = [arrays[0] count]; | |
for(NSUInteger i = 0; i < iterationCount; ++i) | |
{ | |
NSMutableArray *objs = [NSMutableArray array]; | |
for(NSArray *array in arrays) | |
{ | |
[objs addObject:array[i]]; | |
} | |
[zipped addObject:map([objs copy])]; | |
}; | |
va_end(ap); | |
return [zipped copy]; | |
} | |
@interface Person : NSObject | |
@property (nonatomic, copy) NSString *firstName; | |
@property (nonatomic, copy) NSString *lastName; | |
@property (nonatomic, assign) int age; | |
@end | |
@implementation Person | |
-(NSString *)description | |
{ | |
return [NSString stringWithFormat:@"%@ %@, %d", self.firstName, self.lastName, self.age]; | |
} | |
@end | |
int main(int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSArray *firsts = @[ @"Julius", @"Bob", @"Ted" ]; | |
NSArray *lasts = @[ @"Parishy", @"Smith", @"Mosby" ]; | |
NSArray *ages = @[ @20, @42, @30 ]; | |
NSArray *zipped = zip(^Person *(NSArray *objs) { | |
Person *person = [[Person alloc] init]; | |
person.firstName = objs[0]; | |
person.lastName = objs[1]; | |
person.age = [objs[2] integerValue]; | |
return person; | |
}, 3, firsts, lasts, ages); | |
NSLog(@"%@", zipped); | |
} | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2013-08-02 11:37:42.612 Zip[36780:303] ( | |
"Julius Parishy, 20", | |
"Bob Smith, 42", | |
"Ted Mosby, 30" | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment