Skip to content

Instantly share code, notes, and snippets.

@Air-Craft
Created March 14, 2015 20:39
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 Air-Craft/a21a25a192b2fe8df3ef to your computer and use it in GitHub Desktop.
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
/** 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