Skip to content

Instantly share code, notes, and snippets.

@jparishy
Last active December 20, 2015 13:39
Show Gist options
  • Save jparishy/6140873 to your computer and use it in GitHub Desktop.
Save jparishy/6140873 to your computer and use it in GitHub Desktop.
Today in Ugly Code
//
// 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;
}
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