Skip to content

Instantly share code, notes, and snippets.

@kaiobrito
Created January 9, 2018 17:29
Show Gist options
  • Save kaiobrito/789c915e7af8e19dd50119df4e3e2e7b to your computer and use it in GitHub Desktop.
Save kaiobrito/789c915e7af8e19dd50119df4e3e2e7b to your computer and use it in GitHub Desktop.
Functional Programming methods for Objective C
//
// 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
//
// 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