-
Notifications
You must be signed in to change notification settings - Fork 8
/
EKEnumerable.m
310 lines (248 loc) · 7.2 KB
/
EKEnumerable.m
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
//
// EKEnumerable.m
// EnumeratorKit
//
// Created by Adam Sharp on 13/05/13.
// Copyright (c) 2013 Adam Sharp. All rights reserved.
//
#import <objc/runtime.h>
#import "EKEnumerable.h"
#import "EKEnumerator.h"
#import "NSArray+EKEnumerable.h"
#import "NSObject+EKEnumerator.h"
#define SuppressPerformSelectorLeakWarning(Stuff) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \
Stuff; \
_Pragma("clang diagnostic pop") \
} while (0)
@implementation EKEnumerable
#pragma mark - Initialization
- (instancetype)initWithEnumerable:(id<EKEnumerable>)enumerable
{
NSAssert(NO, @"expected -initWithEnumerable: to be implemented");
return nil;
}
#pragma mark - Traversal
- (instancetype)each:(void (^)(id))block
{
NSAssert(NO, @"expected -each: to be implemented");
return nil;
}
- (instancetype)eachWithIndex:(void (^)(id, NSUInteger))block
{
__block NSUInteger i = 0;
[self each:^(id obj) {
block(obj, i++);
}];
return self;
}
#pragma mark Transformations
- (instancetype)map:(id (^)(id))block
{
NSMutableArray *result = [NSMutableArray array];
[self each:^(id obj) {
id mapped = block(obj) ?: [NSNull null];
[result addObject:mapped];
}];
return [[[self class] alloc] initWithEnumerable:result];
}
- (instancetype)mapWithIndex:(id (^)(id, NSUInteger))block
{
__block NSUInteger i = 0;
return [self map:^id(id obj) {
return block(obj, i++);
}];
}
- (instancetype)flattenMap:(id<EKEnumerable> (^)(id))block
{
NSMutableArray *result = [NSMutableArray array];
[self each:^(id obj) {
id mapped = block(obj) ?: [[self class] new];
NSAssert([mapped isKindOfClass:[self class]], @"The block passed to -flattenMap: must return an enumerable of the same type as the receiver.");
[result addObjectsFromArray:[mapped asArray]];
}];
return [[[self class] alloc] initWithEnumerable:result];
}
- (NSDictionary *)mapDictionary:(NSDictionary *(^)(id))block
{
NSMutableDictionary *dict = [NSMutableDictionary new];
[self each:^(id obj) {
NSDictionary *entry = block(obj);
NSAssert([entry count] <= 1, @"Expected a dictionary with no more than 1 entry (%lu entries)", (unsigned long)[entry count]);
[dict addEntriesFromDictionary:entry];
}];
return [dict copy];
}
- (NSDictionary *)wrap:(id<NSCopying> (^)(id))block
{
return [self mapDictionary:^NSDictionary *(id obj) {
return @{block(obj): obj};
}];
}
- (NSDictionary *)groupBy:(id<NSCopying> (^)(id))block
{
NSMutableDictionary *groups = [NSMutableDictionary new];
[self each:^(id obj) {
id<NSCopying> result = block(obj);
id<NSCopying> key = result ? result : [NSNull null];
if (!groups[key]) {
groups[key] = [NSMutableArray new];
}
[groups[key] addObject:obj];
}];
// ensure the chunked arrays are immutable
return [[NSDictionary alloc] initWithDictionary:groups copyItems:YES];
}
- (NSArray *)chunk:(id (^)(id))block
{
NSMutableArray *chunks = [NSMutableArray new];
void (^freeze)(NSMutableArray *, NSInteger) = ^(NSMutableArray *array, NSInteger idx){
if (idx != -1) {
chunks[idx] = [[NSArray alloc] initWithArray:array[idx] copyItems:YES];
}
};
__block NSInteger count = -1;
[self each:^(id obj) {
id result = block(obj);
id key = result ? result : [NSNull null];
if (count == -1 || ![chunks[count][0] isEqual:key]) {
freeze(chunks, count);
count++;
[chunks addObject:[NSMutableArray arrayWithObjects:key, [NSMutableArray arrayWithObject:obj], nil]];
}
else {
[chunks[count][1] addObject:obj];
}
}];
freeze(chunks, count);
return [chunks copy];
}
- (id)reduce:(id (^)(id, id))block
{
return [self reduce:nil withBlock:block];
}
- (id)reduce:(id)initial withBlock:(id (^)(id, id))block
{
// if the initial can be mutable (e.g., @[] or @{}), get a mutable copy
__block id memo = [initial conformsToProtocol:@protocol(NSMutableCopying)] ? [initial mutableCopy] : initial;
[self each:^(id obj) {
if (!memo)
memo = obj;
else
memo = block(memo, obj);
}];
return [memo conformsToProtocol:@protocol(NSCopying)] ? [memo copy] : memo;
}
- (id)inject:(SEL)binaryOperation
{
return [self reduce:^id(id memo, id obj) {
SuppressPerformSelectorLeakWarning(
return [memo performSelector:binaryOperation withObject:obj];
);
}];
}
- (id)inject:(id)initial withOperation:(SEL)binaryOperation
{
return [self reduce:initial withBlock:^id(id memo, id obj) {
SuppressPerformSelectorLeakWarning(
return [memo performSelector:binaryOperation withObject:obj];
);
}];
}
#pragma mark Searching and filtering
- (instancetype)select:(BOOL (^)(id))block
{
NSMutableArray *result = [NSMutableArray array];
[self each:^(id obj) {
if (block(obj)) {
[result addObject:obj];
}
}];
return [[[self class] alloc] initWithEnumerable:result];
}
- (instancetype)filter:(BOOL (^)(id))block
{
return [self select:block];
}
- (instancetype)reject:(BOOL (^)(id))block
{
return [self select:^BOOL(id obj) {
return !block(obj);
}];
}
#pragma mark Sorting
- (NSArray *)sort
{
return [self.asArray sortedArrayUsingSelector:@selector(compare:)];
}
- (NSArray *)sortWith:(NSComparator)comparator
{
return [self.asArray sortedArrayUsingComparator:comparator];
}
- (NSArray *)sortBy:(id (^)(id))block
{
return [[[self map:^(id i){
return @[block(i), i];
}] sort] map:^(id a) {
return a[1];
}];
}
- (id)find:(BOOL (^)(id))block
{
id next;
EKEnumerator *e = self.asEnumerator;
while ((next = e.next)) {
if (block(next)) {
return next;
}
}
return nil;
}
- (BOOL)any:(BOOL (^)(id obj))block
{
return [self find:block] != nil;
}
- (BOOL)all:(BOOL (^)(id obj))block
{
id next;
EKEnumerator *e = self.asEnumerator;
while ((next = e.next)) {
if (!block(next)) {
return NO;
}
}
return YES;
}
#pragma mark Other methods
- (instancetype)take:(NSInteger)number
{
NSMutableArray *result = [NSMutableArray array];
EKEnumerator *e = self.asEnumerator;
NSInteger count = 0;
while (e.peek && (number < 0 || ++count <= number)) {
[result addObject:e.next];
}
return [[[self class] alloc] initWithEnumerable:result];
}
- (NSArray *)asArray
{
return [[NSArray alloc] initWithEnumerable:self];
}
@end
#pragma mark - EKEnumerable mixin
@implementation NSObject (includeEKEnumerable)
+ (void)includeEKEnumerable
{
unsigned int methodCount;
Method *methods = class_copyMethodList([EKEnumerable class], &methodCount);
for (unsigned i = 0; i < methodCount; i++) {
SEL name = method_getName(methods[i]);
IMP imp = method_getImplementation(methods[i]);
const char *types = method_getTypeEncoding(methods[i]);
class_addMethod([self class], name, imp, types);
}
free(methods);
}
@end