Skip to content

Instantly share code, notes, and snippets.

@leandrosilva
Created April 10, 2010 07:31
Show Gist options
  • Save leandrosilva/361893 to your computer and use it in GitHub Desktop.
Save leandrosilva/361893 to your computer and use it in GitHub Desktop.
Functional Objective-C NSArray
//
// NSArray+Functional.h
// DynamicFeatures
//
// Created by Leandro Silva on 4/10/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface NSArray (Functional)
- (void) each: (void (^)(id item))block;
- (NSArray *) map: (id (^)(id obj))block;
- (NSArray *) select: (BOOL (^)(id obj))block;
@end
//
// NSArray+Functional.m
// DynamicFeatures
//
// Created by Leandro Silva on 4/10/10.
// Copyright 2010 __MyCompanyName__. All rights reserved.
//
#import "NSArray+Functional.h"
@implementation NSArray (Functional)
- (void) each: (void (^)(id item))block
{
for (id *object in self) {
block(object);
}
}
- (NSArray *) map: (id (^)(id obj))block
{
NSMutableArray *new = [NSMutableArray array];
for (id obj in self) {
id newObj = block(obj);
[new addObject: newObj ? newObj : [NSNull null]];
}
return new;
}
- (NSArray *) select: (BOOL (^)(id obj))block
{
NSMutableArray *new = [NSMutableArray array];
for (id obj in self) {
if (block(obj)) {
[new addObject: obj];
}
}
return new;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment