diff --git a/Classes/NSArray+ObjectiveSugar.h b/Classes/NSArray+ObjectiveSugar.h index bcf7399..6a37a76 100644 --- a/Classes/NSArray+ObjectiveSugar.h +++ b/Classes/NSArray+ObjectiveSugar.h @@ -218,4 +218,13 @@ - (NSArray *)symmetricDifference:(NSArray *)array; +/** + Groups the collection by result of the block. + + @return A dictionary where the keys are the evaluated result from + the block and the values are arrays of elements in the collection that correspond to the key. +*/ + +- (NSDictionary *)groupBy:(id (^)(id object))block; + @end diff --git a/Classes/NSArray+ObjectiveSugar.m b/Classes/NSArray+ObjectiveSugar.m index 329326f..8d0770d 100644 --- a/Classes/NSArray+ObjectiveSugar.m +++ b/Classes/NSArray+ObjectiveSugar.m @@ -176,6 +176,25 @@ - (NSArray *)reverse { return self.reverseObjectEnumerator.allObjects; } +- (NSDictionary *)groupBy:(id (^)(id object))block { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + + for (id object in self) { + id key = block(object); + + if (![key conformsToProtocol:@protocol(NSCopying)]) { + [NSException raise:NSGenericException format:@"%@ does not conform to ", ^{ + [[theBlock(^{ + [@[@1] groupBy:^id(id object) { + return [[NSObject alloc] init]; + }]; + }) should] raiseWithName:NSGenericException]; + + }); + + }); }); diff --git a/Example/ObjectiveSugarTests/NSDictionaryTests.m b/Example/ObjectiveSugarTests/NSDictionaryTests.m index 2b8a389..e6189aa 100644 --- a/Example/ObjectiveSugarTests/NSDictionaryTests.m +++ b/Example/ObjectiveSugarTests/NSDictionaryTests.m @@ -68,6 +68,20 @@ [[mapped should] equal:sampleDict.allValues]; }); + + it(@"maps new values to existing keys", ^{ + NSDictionary *result = [sampleDict dictionaryMap:^id(id key, id value) { + counter++; + return @([value integerValue] + 1); + }]; + + [[result should] equal:@{ + @"one" : @2, + @"two" : @3, + @"three" : @4 + }]; + + }); }); describe(@"Keys", ^{