Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Objective-C equivalent of JS's `map()` function? [duplicate]

What's the Objective-C equivalent of JS's map() function? Would I just use NSFastEnumeration and apply the function myself?

like image 325
Moshe Avatar asked Jan 19 '11 22:01

Moshe


People also ask

What is difference between map and reduce?

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".

Is map faster than for loop JavaScript?

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.

Does map function modify original array?

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.


1 Answers

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;
}
like image 95
Nicolas Manzini Avatar answered Oct 20 '22 08:10

Nicolas Manzini