Skip to content

Instantly share code, notes, and snippets.

@aminbenarieb
Last active June 2, 2021 05:38
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 aminbenarieb/92b3519678a7c29d6686f84f84fc11c1 to your computer and use it in GitHub Desktop.
Save aminbenarieb/92b3519678a7c29d6686f84f84fc11c1 to your computer and use it in GitHub Desktop.
ABOrderedKeyArray
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NSComparisonResult (^ABOrderedKeyArrayComparator)(id _Nonnull obj1,
id _Nonnull obj2);
@interface ABOrderedKeyArray<__covariant KeyType, __covariant ObjectType>
: NSObject <NSFastEnumeration>
- (instancetype)initWithComparator:(ABOrderedKeyArrayComparator)comparator;
- (nullable id)objectForKey:(KeyType)key;
- (void)insertObject:(ObjectType)object forKey:(KeyType)key;
- (BOOL)removeObjectForKey:(id)key;
- (NSUInteger)indexForObject:(ObjectType)object;
@end
NS_ASSUME_NONNULL_END
#import "ABOrderedKeyArray.h"
@interface ABOrderedKeyArray ()
@property(nonatomic, strong) NSMutableArray<id> *array;
@property(nonatomic, strong) NSMutableDictionary<id, id> *dictionary;
@property(nonatomic, assign) ABOrderedKeyArrayComparator comparator;
@end
@implementation ABOrderedKeyArray
- (instancetype)initWithComparator:(ABOrderedKeyArrayComparator)comparator {
self = [super init];
if (self) {
self.comparator = comparator;
}
return self;
}
- (nullable id)objectForKey:(id)key {
return [self.dictionary objectForKey:key];
}
- (void)insertObject:(id)object forKey:(id)key {
__auto_type index = [self indexForObject:object];
if (index == NSNotFound) {
return;
}
[self.array insertObject:object atIndex:index];
}
- (BOOL)removeObjectForKey:(id)key {
id object = [self.dictionary objectForKey:key];
if (!object) {
return NO;
}
__auto_type index = [self indexForObject:object];
if (index == NSNotFound) {
NSAssert(false, @"Object found in dictionary but not found in array");
return NO;
}
[self.dictionary removeObjectForKey:key];
[self.array removeObjectAtIndex:index];
return YES;
}
- (NSUInteger)indexForObject:(id)object {
return [self.array indexOfObject:object
inSortedRange:NSMakeRange(0, self.array.count)
options:NSBinarySearchingInsertionIndex |
NSBinarySearchingLastEqual
usingComparator:self.comparator];
}
#pragma mark - NSFastEnumeration
- (NSUInteger)
countByEnumeratingWithState:(nonnull NSFastEnumerationState *)state
objects:
(__unsafe_unretained id _Nullable *_Nonnull)buffer
count:(NSUInteger)len {
return [self.array countByEnumeratingWithState:state
objects:buffer
count:len];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment