Last active
June 9, 2016 17:58
-
-
Save darrarski/3a45fb26b61b844db9361dabef7b0e10 to your computer and use it in GitHub Desktop.
Objective-C ArrayMapper
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
#import <Foundation/Foundation.h> | |
@interface ArrayMapper <InputType, OutputType> : NSObject | |
- (nonnull NSArray <OutputType> *)map:(nonnull NSArray <InputType> *)inputArray withBlock:(nonnull OutputType _Nonnull (^)(InputType _Nonnull obj))block; | |
- (nonnull NSArray <OutputType> *)flatMap:(nonnull NSArray <InputType> *)inputArray withBlock:(nonnull OutputType _Nullable (^)(InputType _Nonnull obj))block; | |
@end | |
@implementation ArrayMapper | |
- (nonnull NSArray *)map:(nonnull NSArray *)inputArray withBlock:(nonnull id _Nonnull (^)(id _Nonnull))block | |
{ | |
NSMutableArray *outputArray = [[NSMutableArray alloc] initWithCapacity:inputArray.count]; | |
[inputArray enumerateObjectsUsingBlock:^(id inputObject, NSUInteger idx, BOOL *stop) { | |
[outputArray addObject:block(inputObject)]; | |
}]; | |
return [outputArray copy]; | |
} | |
- (nonnull NSArray *)flatMap:(nonnull NSArray *)inputArray withBlock:(nonnull id _Nullable (^)(id _Nonnull))block | |
{ | |
NSMutableArray *outputArray = [NSMutableArray new]; | |
[inputArray enumerateObjectsUsingBlock:^(id inputObject, NSUInteger idx, BOOL *stop) { | |
id outputObject = block(inputObject); | |
if (outputObject) [outputArray addObject:outputObject]; | |
}]; | |
return [outputArray copy]; | |
} | |
@end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment