Created
January 12, 2012 23:03
-
-
Save sandinist/1603692 to your computer and use it in GitHub Desktop.
NSArray+Map
This file contains 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
#import "NSArray+Map.h" | |
@implementation NSArray (Map) | |
- (NSArray *)map:(id(^)(id))block { | |
NSMutableArray * newArray = [NSMutableArray array]; | |
for (id item in self) { | |
id obj = block(item); | |
[newArray addObject:obj]; | |
} | |
return newArray; | |
} | |
- (id)find:(BOOL(^)(id))block { | |
for (id item in self) { | |
if(block(item))return item; | |
} | |
return nil; | |
} | |
- (NSArray *)findAll:(BOOL(^)(id))block { | |
NSMutableArray * newArray = [NSMutableArray array]; | |
for (id item in self) { | |
if(block(item)) [newArray addObject:item]; | |
} | |
return newArray; | |
} | |
@end | |
#import "Kiwi.h" | |
#import "NSArray+Map.h" | |
SPEC_BEGIN(NSArray_MapSpec) | |
describe(@"Map", ^{ | |
it(@"works", ^{ | |
NSArray * array = [NSArray arrayWithObjects:@"A", @"B", @"C",nil]; | |
NSArray * result = [array map:^(id item) { | |
return [NSString stringWithFormat:@"mapped%@", item]; | |
}]; | |
[[[result objectAtIndex:0] should] equal:@"mappedA"]; | |
[[[result objectAtIndex:1] should] equal:@"mappedB"]; | |
[[[result objectAtIndex:2] should] equal:@"mappedC"]; | |
}); | |
}); | |
describe(@"FindAll", ^{ | |
it(@"works", ^{ | |
NSArray * array = [NSArray arrayWithObjects:@"ABC", @"BCD", @"CDE",nil]; | |
NSArray * result = [array findAll:^(id item) { | |
NSRange match = [item rangeOfString:@"CD"]; | |
return (BOOL)(match.location != NSNotFound); | |
}]; | |
[[[result objectAtIndex:0] should] equal:@"BCD"]; | |
[[[result objectAtIndex:1] should] equal:@"CDE"]; | |
}); | |
}); | |
describe(@"Find", ^{ | |
it(@"works", ^{ | |
NSArray * array = [NSArray arrayWithObjects:@"ABC", @"BCD", @"CDE",nil]; | |
NSString * result = [array find:^(id item) { | |
NSRange match = [item rangeOfString:@"CD"]; | |
return (BOOL)(match.location != NSNotFound); | |
}]; | |
[[result should] equal:@"BCD"]; | |
}); | |
}); | |
SPEC_END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment