//
//  MPArrayCache.m
//  MathPad
//
//  Created by Kim Wittenburg on 31.08.14.
//  Copyright (c) 2014 Kim Wittenburg. All rights reserved.
//

#import "MPArrayCache.h"

@implementation MPArrayCache {
    NSUInteger lastIndex;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        lastIndex = 0;
        _cache = [[NSCache alloc] init];
    }
    return self;
}

- (void)cacheObject:(id)object
           forIndex:(NSUInteger)index
{
    [_cache setObject:object
               forKey:@(index)];
    if (index > lastIndex) {
        lastIndex = index;
    }
}

- (id)cachedObjectForIndex:(NSUInteger)index
{
    return [_cache objectForKey:@(index)];
}

- (void)clearCacheAtIndex:(NSUInteger)index replacementLength:(NSUInteger)replacementLength
{
    [_cache removeObjectForKey:@(index)];
    for (NSUInteger i = index+1; i < lastIndex; i++) {
        id object = [_cache objectForKey:@(i)];
        if (object) {
            [_cache removeObjectForKey:@(i)];
        }
    }
    lastIndex += replacementLength - 1;
}

- (void)clearCacheInRange:(NSRange)range replacementLength:(NSUInteger)replacementLength;

- (void)replaceCachedObjectAtIndex:(NSUInteger)index
                       withObjects:(NSArray *)objects;
- (void)replaceCachedObjectsInRange:(NSRange)range
                        withObjects:(NSArray *)objects;

@end
