Skip to content

Instantly share code, notes, and snippets.

@janodev
Created January 31, 2013 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/4683470 to your computer and use it in GitHub Desktop.
Save janodev/4683470 to your computer and use it in GitHub Desktop.
14589365
#import <Foundation/Foundation.h>
typedef NS_ENUM(unsigned char, MyTreeVisitingOrder) {
MyTreeOrderDepthFirst,
MyTreeOrderValueFirst
};
#define Tree NSObject<MyTree>
@protocol MyTree
@property (nonatomic,strong) NSObject<NSCopying>* key;
@property (nonatomic,strong) NSObject *value;
@property (nonatomic,strong) NSMutableDictionary *children;
-(void) insertChild:(Tree*)node;
-(void) each:(void(^)(NSObject*))block order:(MyTreeVisitingOrder)order;
@end
@interface TreeImpl : NSObject <MyTree>
-(id) init __attribute__((unavailable("disabled")));
@end
@implementation TreeImpl
@synthesize key = _key;
@synthesize value = _value;
@synthesize children = _children;
-(id) initWithKey:(NSObject<NSCopying>*)key value:(NSObject*)value {
self = [super init];
if (self){
_key = key;
_value = value;
_children = [NSMutableDictionary new];
}
return self;
}
-(void) insertChild:(Tree*)node {
[_children setObject:node forKey:node.key];
}
-(void) each:(void(^)(NSObject*))block order:(MyTreeVisitingOrder)order {
switch (order) {
case MyTreeOrderDepthFirst:{
if (_children) {
for (id key in _children){
[[_children objectForKey:key] each:block order:order];
}
}
block(_value);
break;
}
case MyTreeOrderValueFirst:{
block(_value);
if (_children) {
for (id key in _children){
[[_children objectForKey:key] each:block order:order];
}
}
break;
}
}
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
TreeImpl *a = [[TreeImpl alloc] initWithKey:@"A" value:@"A"];
TreeImpl *b = [[TreeImpl alloc] initWithKey:@"B" value:@"B"];
TreeImpl *c = [[TreeImpl alloc] initWithKey:@"C" value:@"C"];
[a insertChild:b];
[a insertChild:c];
[a each:^(NSObject* value) {
NSLog(@"> %@",value);
} order:MyTreeOrderValueFirst];
return EXIT_SUCCESS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment