Last active
January 18, 2016 02:22
-
-
Save rhysforyou/83fe424236b01347f5ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import <Foundation/Foundation.h> | |
| @interface NSArray (FunctionalPrimitives) | |
| - (NSArray *)flatten; | |
| - (NSArray *)reverse; | |
| - (NSArray *)map:(id (^)(id))transform; | |
| - (NSArray *)filter:(BOOL (^)(id))predicateBlock; | |
| - (NSArray *)foldRightWithStart:(id)start reduce:(id (^)(id item, id result))reduce; | |
| - (NSArray *)foldRightWithStart:(id)start reduce:(id (^)(id item, id result))reduce; | |
| - (NSArray *)flatMap:(id (^)(id))transform; | |
| @end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #import "NSArray+FunctionalPrimitives.h" | |
| @implementation NSArray (FunctionalPrimitives) | |
| - (NSArray *)flatten { | |
| NSMutableArray *result = [NSMutableArray new]; | |
| for (id item in self) { | |
| if ([item isKindOfClass:[NSArray class]]) { | |
| [result addObjectsFromArray:[item flatten]]; | |
| } else { | |
| [result addObject:item]; | |
| } | |
| } | |
| return result; | |
| } | |
| - (NSArray *)reverse { | |
| NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:self.count]; | |
| for (id item in [self reverseObjectEnumerator]) { | |
| [results addObject:item]; | |
| } | |
| return results; | |
| } | |
| - (NSArray *)map:(id (^)(id))transform { | |
| NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:self.count]; | |
| for (id item in self) { | |
| [results addObject:transform(item)]; | |
| } | |
| return [results copy]; | |
| } | |
| - (NSArray *)filter:(BOOL (^)(id))predicateBlock { | |
| return [self filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) { | |
| return predicateBlock(evaluatedObject); | |
| }]]; | |
| } | |
| - (NSArray *)foldLeftWithStart:(id)start reduce:(id (^)(id, id))reduce { | |
| id result = start; | |
| for (id item in self) { | |
| result = reduce(item, result); | |
| } | |
| return result; | |
| } | |
| - (NSArray *)foldRightWithStart:(id)start reduce:(id (^)(id, id))reduce | |
| { | |
| return [[self reverse] foldLeftWithStart:start reduce:reduce]; | |
| } | |
| - (NSArray *)flatMap:(id (^)(id))transform { | |
| return [[self map:transform] flatten]; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment