Skip to content
This repository was archived by the owner on Dec 12, 2018. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Classes/NSArray+ObjectiveSugar.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@
*/
- (id)sample;

/**
Take random `numberOfElements` out of the array, or the maximum amount of
elements if it is less.

@param Number of random elements to take from array
@return An array of elements
*/
- (NSArray *)sample:(NSUInteger)numberOfElements;

/// Alias for -sample
- (id)anyObject;

Expand Down
13 changes: 13 additions & 0 deletions Classes/NSArray+ObjectiveSugar.m
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ - (id)sample {
return self[index];
}

- (NSArray *)sample:(NSUInteger)numberOfElements {
if (numberOfElements > self.count) {
numberOfElements = self.count;
}
NSMutableArray *array = [NSMutableArray arrayWithArray:self];
for (NSUInteger i = 0; i < numberOfElements; i++) {
NSInteger size = array.count - i;
NSInteger r = (arc4random() % size) + i;
[array exchangeObjectAtIndex:i withObjectAtIndex:r];
}
return [array subarrayWithRange:NSMakeRange(0, numberOfElements)];
}

- (id)objectForKeyedSubscript:(id)key {
if ([key isKindOfClass:[NSString class]])
return [self subarrayWithRange:[self rangeFromString:key]];
Expand Down
11 changes: 11 additions & 0 deletions Example/ObjectiveSugarTests/NSArrayCategoriesTests.m
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@
NSArray *emptyArray = @[];
[emptyArray.sample shouldBeNil];
});

it(@"-sample: returns an array of random elements with given count", ^{
NSArray *result = [sampleArray sample:2];
[[result should] haveCountOf:2];
[[sampleArray should] containObjectsInArray:result];
});

it(@"-sample: returns an array of maximum amount when it is less than given count" , ^{
[[[sampleArray sample:12] should] haveCountOf:3];
[[[sampleArray sample:-1] should] haveCountOf:3];
});

context(@"Iterating using block", ^{

Expand Down