Objective-C bounded LRU cache with timestamp recency
Objective-C
#import <Foundation/Foundation.h>
static id LRUGet(NSMutableDictionary *cache, NSString *key) {
NSDictionary *entry = cache[key];
if (!entry) return nil;
entry = @{@"value": entry[@"value"], @"used": @([[NSDate date] timeIntervalSince1970])};
cache[key] = entry;
return entry[@"value"];
}
static void LRUPut(NSMutableDictionary *cache, NSString *key, id value, NSUInteger limit) {
cache[key] = @{@"value": value ?: [NSNull null], @"used": @([[NSDate date] timeIntervalSince1970])};
while (cache.count > limit) {
NSString *oldest = [cache keysSortedByValueUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
return [a[@"used"] compare:b[@"used"]];
}].firstObject;
[cache removeObjectForKey:oldest];
}
}