Skip to content

Instantly share code, notes, and snippets.

@mirkokiefer
Created February 21, 2014 10:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mirkokiefer/9132311 to your computer and use it in GitHub Desktop.
Save mirkokiefer/9132311 to your computer and use it in GitHub Desktop.
Compute a position string between two other strings for concurrently sorting lists based on a lexicographically sortable position property.
+ (NSString *)positionBetweenPrevious:(NSString *)previous next:(NSString *)next {
if (!previous) {
previous = @"0";
}
if (!next) {
next = @"z";
}
NSString *chars = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
NSMutableString *betweenPosition = [NSMutableString string];
NSUInteger index = 0;
while (YES) {
NSRange range = NSMakeRange(index, 1);
NSUInteger previousIndex = 0;
NSUInteger nextIndex = chars.length - 1;
if (index < previous.length) {
NSString *previousChar = [previous substringWithRange:range];
previousIndex = [chars rangeOfString:previousChar].location;
}
if (index < next.length) {
NSString *nextChar = [next substringWithRange:range];
nextIndex = [chars rangeOfString:nextChar].location;
}
index += 1;
NSUInteger betweenIndex;
if (previousIndex >= nextIndex) {
betweenIndex = previousIndex;
} else {
betweenIndex = (previousIndex + nextIndex) / 2;
}
NSString *betweenChar = [chars substringWithRange:NSMakeRange(betweenIndex, 1)];
[betweenPosition appendString:betweenChar];
BOOL positionAfterPrevious = [previous compare:betweenPosition] == NSOrderedAscending;
BOOL positionBeforeNext = [betweenPosition compare:next] == NSOrderedAscending;
BOOL lastCharNotFirstPossibleChar = betweenIndex != 0;
if (positionAfterPrevious && positionBeforeNext && lastCharNotFirstPossibleChar) {
return betweenPosition;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment