Skip to content

Commit

Permalink
fmap for Set
Browse files Browse the repository at this point in the history
  • Loading branch information
kkazuo committed Dec 6, 2014
1 parent caa9e6e commit 7c4c62d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions NSSet+fmap.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#import "YOLO.ph"

@implementation NSSet (YOLO)

- (NSSet *(^)(id (^)(id)))fmap {
return ^(id (^block)(id)) {
id mapped[self.count];
NSUInteger ii = 0;
for (id mappable in self) {
id o = block(mappable);
if (o)
mapped[ii++] = o;
}
return [[self.class alloc] initWithObjects:mapped count:ii];
};
}

@end
7 changes: 7 additions & 0 deletions YOLO.h
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,13 @@ clear.
- (NSSet *(^)(void (^)(id o)))each;
#endif

#ifdef YOLO_FMAP
/**
@see NSArray's -fmap
*/
- (NSSet *(^)(id (^)(id obj)))fmap;
#endif

@end


Expand Down
19 changes: 19 additions & 0 deletions tests
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,25 @@ int main() {
XCTAssertTrue([bb isKindOfClass:[NSMutableArray class]]);
}
- (void)testSetFmap {
NSSet *aa = [NSSet setWithObjects:@1, @2, @3, nil];
XCTAssertEqualObjects((aa.fmap(^(id obj) { return obj; })), aa);
XCTAssertEqualObjects((aa.fmap(^(id obj) { return (id)nil; })), [NSSet set]);
id bb = aa.fmap(^(id obj) {
return @([obj intValue] * [obj intValue]);
});
XCTAssertEqualObjects(bb, ([NSSet setWithObjects:@1, @4, @9, nil]));
XCTAssertFalse([bb isKindOfClass:[NSMutableSet class]]);
bb = ((NSSet *)aa.mutableCopy).fmap(^(id obj) {
return @([obj intValue] * [obj intValue]);
});
XCTAssertEqualObjects(bb, ([NSSet setWithObjects:@1, @4, @9, nil]));
XCTAssertTrue([bb isKindOfClass:[NSMutableSet class]]);
}
- (void)testDictionaryFmap {
XCTAssertEqualObjects(@{}, (@{}.fmap(^(id obj) { return obj; })));
Expand Down

0 comments on commit 7c4c62d

Please sign in to comment.