Created
January 9, 2018 17:29
-
-
Save kaiobrito/789c915e7af8e19dd50119df4e3e2e7b to your computer and use it in GitHub Desktop.
Functional Programming methods for Objective C
This file contains 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
// | |
// NSArray+FP.h | |
// | |
// Created by Kaio Brito on 09/01/18. | |
// | |
#import <Foundation/Foundation.h> | |
typedef id(^MapBlock)(id); | |
typedef BOOL(^FilterBlock)(id); | |
typedef id(^ReduceBlock)(id, id); | |
@interface NSArray (FP) | |
- (id) reduce: (ReduceBlock) block initial: (id) initialValue; | |
- (NSArray *) filter: (FilterBlock) block; | |
- (NSArray *) flatMap: (MapBlock) block; | |
- (NSArray *) map: (MapBlock) block; | |
@end |
This file contains 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
// | |
// NSArray+FP.m | |
// | |
// Created by Kaio Brito on 09/01/18. | |
// | |
@implementation NSArray (FP) | |
- (NSArray *) map: (MapBlock) block { | |
NSMutableArray *resultArray = [[NSMutableArray alloc] init]; | |
for (id object in self) { | |
[resultArray addObject:block(object)]; | |
} | |
return resultArray; | |
} | |
- (NSArray *) filter: (FilterBlock) block { | |
return [self filteredArrayUsingPredicate: [NSPredicate predicateWithBlock:^BOOL(id _Nullable evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) { | |
return block(evaluatedObject); | |
}]]; | |
} | |
- (NSArray *) flatMap: (MapBlock) block { | |
return [[self map:block] filter:^BOOL(id object) { | |
return object != nil; | |
}]; | |
} | |
- (id) reduce: (ReduceBlock) block initial: (id) initialValue { | |
for (id item in self) { | |
initialValue = block(initialValue, item); | |
} | |
return initialValue; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment