diff --git a/Riot/Categories/NSArray+Element.h b/Riot/Categories/NSArray+Element.h new file mode 100644 index 000000000..f8ef1a857 --- /dev/null +++ b/Riot/Categories/NSArray+Element.h @@ -0,0 +1,31 @@ +// +// Copyright 2021 New Vector Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface NSArray (Element) + +- (NSArray *)vc_map:(id (^)(id obj))block; + +- (NSArray *)vc_compactMap:(id _Nullable (^)(id obj))block; + +- (NSArray *)vc_flatMap:(NSArray* (^)(id obj))block; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Riot/Categories/NSArray+Element.m b/Riot/Categories/NSArray+Element.m new file mode 100644 index 000000000..35427c9df --- /dev/null +++ b/Riot/Categories/NSArray+Element.m @@ -0,0 +1,55 @@ +// +// Copyright 2021 New Vector Ltd +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import "NSArray+Element.h" + +@implementation NSArray (Element) + +- (NSArray *)vc_map:(id (^)(id obj))block +{ + NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count]; + [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) + { + [result addObject:block(obj)]; + }]; + return result; +} + +- (NSArray *)vc_compactMap:(id _Nullable (^)(id obj))block +{ + NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count]; + [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) + { + id mappedObject = block(obj); + if (mappedObject) + { + [result addObject:mappedObject]; + } + }]; + return result; +} + +- (NSArray *)vc_flatMap:(NSArray* (^)(id obj))block +{ + NSMutableArray *result = [NSMutableArray arrayWithCapacity:self.count]; + [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) + { + [result addObjectsFromArray:block(obj)]; + }]; + return result; +} + +@end