-
Notifications
You must be signed in to change notification settings - Fork 1
/
ATFunctionalCollectionExtensions.m
95 lines (74 loc) · 2.63 KB
/
ATFunctionalCollectionExtensions.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
//
// ATFunctionalCollectionExtensions.m
// Azure Talon
//
// Created by Kenneth Ballenegger on 5/24/12.
// Copyright (c) 2012 Kenneth Ballenegger (kswizz.com). All rights reserved.
//
#import "ATFunctionalCollectionExtensions.h"
@implementation NSArray (ATFunctionalCollectionExtensions)
- (void)each:(void(^)(id object))block {
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { block(obj); }];
}
- (NSArray *)map:(id(^)(id object))block {
return [[[self inject:^(NSMutableArray *acc, id obj) {
[acc addObject:block(obj)]; return acc;
} initial:[NSMutableArray array]] copy] autorelease];
}
- (id)reduce:(id(^)(id a, id b))block {
if (self.count == 0) return nil;
id accumulator = [self objectAtIndex:0];
for (NSUInteger i = 0; i < self.count-1; i++) {
accumulator = block(accumulator, [self objectAtIndex:i+1]);
}
return accumulator;
}
- (NSArray *)filter:(BOOL(^)(id object))block {
return [[[self inject:^(NSMutableArray *acc, id obj) {
if (block(obj)) [acc addObject:obj]; return acc;
} initial:[NSMutableArray array]] copy] autorelease];
}
- (id)inject:(id(^)(id accumulator, id object))block initial:(id)accumulator {
__block id acc = accumulator;
[self each:^(id obj){
acc = block(acc, obj);
}];
return acc;
}
@end
@implementation NSDictionary (ATFunctionalCollectionExtensions)
- (void)each:(void(^)(id key, id object))block {
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { block(key, obj); }];
}
- (NSDictionary *)map:(id(^)(id key, id object))block {
return [[[self inject:^(NSMutableDictionary *acc, id key, id obj) {
[acc setObject:block(key, obj) forKey:key]; return acc;
} initial:[NSMutableDictionary dictionary]] copy] autorelease];
}
- (NSDictionary *)filter:(BOOL(^)(id key, id object))block {
return [[[self inject:^(NSMutableDictionary *acc, id key, id obj) {
if (block(key, obj)) [acc setObject:obj forKey:key]; return acc;
} initial:[NSMutableArray array]] copy] autorelease];
}
- (id)inject:(id(^)(id accumulator, id key, id object))block initial:(id)accumulator {
__block id acc = accumulator;
[self each:^(id key, id obj){
acc = block(acc, key, obj);
}];
return acc;
}
- (NSArray *)keys {
NSMutableArray *acc = [NSMutableArray array];
for (id key in self) {
[acc addObject:key];
}
return [[acc copy] autorelease];
}
- (NSArray *)objects {
NSMutableArray *acc = [NSMutableArray array];
for (id obj in self.objectEnumerator) {
[acc addObject:obj];
}
return [[acc copy] autorelease];
}
@end