-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathMACollectionUtilities.m
105 lines (88 loc) · 2.08 KB
/
MACollectionUtilities.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
//
// MACollectionUtilities.m
// MACollectionUtilities
//
// Created by Michael Ash on 10/11/10.
// Copyright 2010 Michael Ash. All rights reserved.
//
#import "MACollectionUtilities.h"
@implementation NSArray (MACollectionUtilities)
- (NSArray *)ma_map: (id (^)(id obj))block
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity: [self count]];
for(id obj in self)
[array addObject: block(obj)];
return array;
}
- (NSArray *)ma_select: (BOOL (^)(id obj))block
{
NSMutableArray *array = [NSMutableArray array];
for(id obj in self)
if(block(obj))
[array addObject: obj];
return array;
}
- (id)ma_match: (BOOL (^)(id obj))block
{
for(id obj in self)
if(block(obj))
return obj;
return nil;
}
- (id)ma_reduce: (id)initial block: (id (^)(id a, id b))block
{
id a = initial;
for(id b in self)
a = block(a, b);
return a;
}
- (NSArray *)ma_sorted: (BOOL (^)(id a, id b))lessThan
{
return [self sortedArrayUsingComparator: ^NSComparisonResult(id a, id b) {
if(lessThan(a, b))
return NSOrderedAscending;
else if(lessThan(b, a))
return NSOrderedDescending;
else
return NSOrderedSame;
}];
}
- (void)ma_do: (void (^)(id obj))block
{
for(id obj in self)
block(obj);
}
@end
@implementation NSSet (MACollectionUtilities)
- (NSSet *)ma_map: (id (^)(id obj))block
{
NSMutableSet *set = [NSMutableSet setWithCapacity: [self count]];
for(id obj in self)
[set addObject: block(obj)];
return set;
}
- (NSSet *)ma_select: (BOOL (^)(id obj))block
{
NSMutableSet *set = [NSMutableSet set];
for(id obj in self)
if(block(obj))
[set addObject: obj];
return set;
}
- (id)ma_match: (BOOL (^)(id obj))block
{
for(id obj in self)
if(block(obj))
return obj;
return nil;
}
- (NSArray *)ma_sorted: (BOOL (^)(id a, id b))lessThan
{
return [[self allObjects] ma_sorted: lessThan];
}
- (void)ma_do: (void (^)(id obj))block
{
for(id obj in self)
block(obj);
}
@end