Created
February 21, 2014 10:46
-
-
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.
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
+ (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