Merge pull request #35 in BPHVB/mvm_core from feature/array_category to develop

* commit 'e56f429834d9d6561ffcee5739dbf4c1bf02f2c1':
  nullable fixes
  fucntional methods for array
This commit is contained in:
Sommer, Patrick 2018-09-12 09:57:22 -04:00
commit 099aa25655
2 changed files with 36 additions and 1 deletions

View File

@ -38,6 +38,9 @@
- (nonnull NSString *)stringAtIndex:(NSUInteger)index;
// Maps this array to a new array of T objects given a conversion block. Objective-C implementation of Swift's map. https://developer.apple.com/documentation/swift/array/2908681-map
- (nonnull NSArray *) map:(id _Nullable (^_Nonnull)(id _Nonnull obj))mapBlock;
- (nonnull NSArray *)map:(id _Nullable (^_Nonnull)(id _Nonnull obj))mapBlock;
- (nonnull NSArray *)filter:(BOOL (^_Nullable)(id _Nonnull obj))block;
- (nonnull id)reduce:(id _Nonnull)initial block:(id _Nonnull (^_Nonnull)(id _Nonnull obj1,id _Nonnull obj2))block;
- (nullable NSArray *)flatMap:(id _Nullable (^_Nonnull)(id _Nullable obj))block;
@end

View File

@ -96,4 +96,36 @@
return mapped;
}
- (NSArray *)filter:(BOOL (^)(id obj))block {
NSMutableArray *mutableArray = [NSMutableArray new];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (block(obj) == YES) {
[mutableArray addObject:obj];
}
}];
return mutableArray;
}
- (id)reduce:(id)initial block:(id (^)(id obj1, id obj2))block {
__block id obj = initial;
[self enumerateObjectsUsingBlock:^(id _obj, NSUInteger idx, BOOL *stop) {
obj = block(obj, _obj);
}];
return obj;
}
- (NSArray *)flatMap:(id (^)(id obj))block {
NSMutableArray *mutableArray = [NSMutableArray new];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id _obj = block(obj);
if ([_obj isKindOfClass:[NSArray class]]) {
NSArray *_array = [_obj flatMap:block];
[mutableArray addObjectsFromArray:_array];
return;
}
[mutableArray addObject:_obj];
}];
return mutableArray;
}
@end