What's the Objective-C equivalent of JS's map()
function? Would I just use NSFastEnumeration and apply the function myself?
Generally "map" means converting a series of inputs to an equal length series of outputs while "reduce" means converting a series of inputs into a smaller number of outputs. What people mean by "map-reduce" is usually construed to mean "transform, possibly in parallel, combine serially".
Speed Comparison The code looks very similar but the results are the opposite. Some tests said forEach is faster and some said map is faster.
map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.
Category function for NSArray an alternative
- (NSArray *)map:(id(^)(id, BOOL *))block {
NSMutableArray * array = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
id newObject = block(obj,stop);
if (newObject == nil) {
newObject = [NSNull null];
}
[array addObject:newObject];
}];
return array.copy;
}
Category function for NSMutableArray an alternative
- (NSMutableArray *)map:(id(^)(id))block {
NSEnumerator * enumerator = ((NSArray *)self.copy).objectEnumerator;
id obj; NSUInteger idx = 0;
while ((obj = enumerator.nextObject)) {
self[idx] = block(obj) ?: [NSNull null];
idx++;
}
return self;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With