Permalink
Browse files

[NEW] Started NSDictionary equivalents

  • Loading branch information...
1 parent d3a5b11 commit 3529bd89b5d08002ffc4128bfbadaf518eb4f297 @crafterm committed Nov 17, 2010
Showing with 70 additions and 0 deletions.
  1. +20 −0 NSDictionary+Enumerable.h
  2. +50 −0 NSDictionary+Enumerable.m
View
@@ -0,0 +1,20 @@
+//
+// NSDictionary+Enumerable.h
+// MRCEnumerable
+//
+// Created by Marcus Crafter on 17/11/10.
+// Copyright 2010 Red Artisan. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+
+@interface NSDictionary (Enumerable)
+
+- (void)each:(void (^)(id key, id obj))block;
+- (id)inject:(id)m :(id (^)(id m, id key, id obj))block;
+- (NSDictionary *)select:(BOOL (^)(id key, id obj))block;
+- (NSDictionary *)reject:(BOOL (^)(id key, id obj))block;
+- (id)detect:(BOOL (^)(id key, id obj))block;
+
+@end
View
@@ -0,0 +1,50 @@
+//
+// NSDictionary+Enumerable.m
+// MRCEnumerable
+//
+// Created by Marcus Crafter on 17/11/10.
+// Copyright 2010 Red Artisan. All rights reserved.
+//
+
+#import "NSDictionary+Enumerable.h"
+
+
+@implementation NSDictionary (Enumerable)
+
+- (void)each:(void (^)(id key, id obj))block {
+ [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { block(key, obj); }];
+}
+
+- (id)inject:(id)m :(id (^)(id m, id key, id obj))block {
+ id result = m ? m : [self objectForKey:[[self allKeys] firstObject]]; // REVISIT: correct semantics?
+
+ for (id key in [self allKeys]) {
+ result = block(result, key, [self objectForKey:key]);
+ }
+
+ return result;
+}
+
+- (NSDictionary *)select:(BOOL (^)(id key, id obj))block {
+ return [self inject:[NSMutableDictionary dictionary] :^(id m, id key, id obj) {
+ if (block(key, obj) == YES) [m setValue:obj forKey:key];
+ return m;
+ }];
+}
+
+- (NSDictionary *)reject:(BOOL (^)(id key, id obj))block {
+ return [self inject:[NSMutableDictionary dictionary] :^(id m, id key, id obj) {
+ if (block(key, obj) == NO) [m setValue:obj forKey:key];
+ return m;
+ }];
+}
+
+- (id)detect:(BOOL (^)(id key, id obj))block {
+ for (id key in [self allKeys]) {
+ if (block(key, [self objectForKey:key])) return key;
+ }
+
+ return nil;
+}
+
+@end

0 comments on commit 3529bd8

Please sign in to comment.