forked from ColinEberhardt/LinqToObjectiveC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSDictionary+LinqExtensions.m
82 lines (72 loc) · 2.08 KB
/
NSDictionary+LinqExtensions.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
//
// NSDictionary+LinqExtensions.m
// LinqToObjectiveC
//
// Created by Colin Eberhardt on 25/02/2013.
// Copyright (c) 2013 Colin Eberhardt. All rights reserved.
//
#import "NSDictionary+LinqExtensions.h"
@implementation NSDictionary (LinqExtensions)
- (NSDictionary *)where:(KeyValueCondition)predicate
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (predicate(key, obj)) {
[result setObject:obj forKey:key];
}
}];
return result;
}
- (NSDictionary *)select:(KeyValueSelector)selector
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[result setObject:selector(key, obj) forKey:key];
}];
return result;
}
- (NSArray *)toArray:(KeyValueSelector)selector
{
NSMutableArray* result = [[NSMutableArray alloc] init];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[result addObject:selector(key, obj)];
}];
return result;
}
- (BOOL)all:(KeyValueCondition)condition
{
__block BOOL all = TRUE;
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (!condition(key, obj)){
all = FALSE;
*stop = TRUE;
}
}];
return all;
}
- (BOOL)any:(KeyValueCondition)condition
{
__block BOOL any = FALSE;
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (condition(key, obj)){
any = TRUE;
*stop = TRUE;
}
}];
return any;
}
- (NSUInteger)count:(KeyValueCondition)condition
{
return [self where:condition].count;
}
- (NSDictionary *)merge:(NSDictionary *)dictionary
{
NSMutableDictionary* result = [[NSMutableDictionary alloc] initWithDictionary:self];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if (![result objectForKey:key]) {
[result setObject:obj forKey:key];
}
}];
return result;
}
@end