supermarin / ObjectiveSugar

ObjectiveC additions for humans. Ruby style.
MIT License
2.17k stars 190 forks source link

Add one function : map NSArray and skip someone #120

Open Yrocky opened 6 years ago

Yrocky commented 6 years ago

Sometimes not only need to map out an array, but also need to conditional mapping. Reference to NSArray's block traversal method - (void) enumerateObjectsUsingBlock: (void (NS_NOESCAPE ^) (ObjectType obj, NSUInteger idx, BOOL * stop)) block.

Add a skip option for the mapping method:

- (NSArray *) mm_mapWithskip:(id (^)(id obj, BOOL *skip))callback{

    NSMutableArray * _self = [NSMutableArray arrayWithCapacity:self.count];

    for( id obj in self ){

        BOOL skip = NO;

        id mapObj = callback(obj, &skip);

        if( !skip ){
            [_self addObject:mapObj];
        }
    }
    return [_self copy];
}

Refer to this answer