forked from BlocksKit/BlocksKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSArray+BlocksKit.m
More file actions
executable file
·95 lines (67 loc) · 1.98 KB
/
Copy pathNSArray+BlocksKit.m
File metadata and controls
executable file
·95 lines (67 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// NSArray+BlocksKit.m
// BlocksKit
//
#import "NSArray+BlocksKit.h"
@implementation NSArray (BlocksKit)
- (void)each:(BKSenderBlock)block {
NSParameterAssert(block != nil);
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
block(obj);
}];
}
- (void)apply:(BKSenderBlock)block {
NSParameterAssert(block != nil);
[self enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
block(obj);
}];
}
- (id)match:(BKValidationBlock)block {
NSParameterAssert(block != nil);
NSUInteger index = [self indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return block(obj);
}];
if (index == NSNotFound)
return nil;
return [self objectAtIndex:index];
}
- (NSArray *)select:(BKValidationBlock)block {
NSParameterAssert(block != nil);
NSArray *result = [self objectsAtIndexes:[self indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return block(obj);
}]];
if (!result.count)
return nil;
return result;
}
- (NSArray *)reject:(BKValidationBlock)block {
NSParameterAssert(block != nil);
NSArray *result = [self objectsAtIndexes:[self indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return !block(obj);
}]];
if (!result.count)
return nil;
return result;
}
- (NSArray *)map:(BKTransformBlock)block {
NSParameterAssert(block != nil);
NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id value = block(obj);
if (!value)
value = [NSNull null];
[result addObject:value];
}];
return result;
}
- (id)reduce:(id)initial withBlock:(BKAccumulationBlock)block {
NSParameterAssert(block != nil);
__block id result = [initial retain];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id new = block(result, obj);
[result release];
result = [new retain];
}];
return [result autorelease];
}
@end