Created
March 14, 2015 20:39
-
-
Save Air-Craft/a21a25a192b2fe8df3ef to your computer and use it in GitHub Desktop.
Utility for inserting new entries in set X preserving order defined in set M #objective-c #cocoa #collections #sorting #intermediate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Utility for inserting new entries in set X preserving order defined in set M */ | |
- (void)_addEntry:(id)entryToInsert toSet:(NSMutableOrderedSet *)mutatingSet respectingOrderIn:(NSMutableOrderedSet *)masterSet | |
{ | |
NSInteger entryIdxInMaster = [masterSet indexOfObject:entryToInsert]; | |
NSAssert(entryIdxInMaster != NSNotFound, @"The setWithOrder must contain the entryToInsert"); | |
// Loop through the set and find the index of the place to insert the new entry | |
__block NSInteger idxToInsertBefore = NSNotFound; | |
[mutatingSet enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) | |
{ | |
NSInteger objIdxInMaster = [masterSet indexOfObject:obj]; | |
if (entryIdxInMaster < objIdxInMaster) | |
{ | |
idxToInsertBefore = idx; // = idx of the obj in the mutating set | |
*stop = YES; | |
} | |
}]; | |
// If not found then the new entry's idx in the masterSet was higher than all the existing ones so append it | |
if (idxToInsertBefore == NSNotFound) { | |
[mutatingSet addObject:entryToInsert]; | |
} else { | |
[mutatingSet insertObject:entryToInsert atIndex:idxToInsertBefore]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment