% Cache - Holds objects for display. 

% Copyright 2012 The MathWorks, Inc.

classdef ( Hidden ) Cache < handle
    
    properties ( Hidden, Access = private )
        % Index is the location in the cache map to insert the next object.
        NextIndex
        CacheMap
    end
    
    methods
        function obj = Cache(cacheLength)
            % Initialize index to 1 the first time the cache is
            % implemented.
            obj.NextIndex = 1;
            obj.CacheMap = cell( cacheLength , 2 );
        end
  
        function add( obj, key, value )
            % Add an object to the cache 
            obj.CacheMap(obj.NextIndex, :) = { key value };
            % MATLAB array indices start at 1, not 0 so we add +1 to the
            % normal modular arithmetic for queues. 
            obj.NextIndex = mod( obj.NextIndex, obj.getCacheLength ) + 1;
        end
        
        function value = get( obj, key )
            % In most workflows, the value we want to return will
            % be the last value entered into the map, so we want to look 
            % through the keys starting with the last key added and moving 
            % to the next-to-last key added and then the next-to-next-last
            % key added and so on.  
            cacheLen = obj.getCacheLength;
            order = (0:cacheLen-1) + (obj.NextIndex - 1);
            order = mod( order - 1, cacheLen ) + 1;
            
            for i = order
                if isequal( obj.CacheMap{i, 1}, key )
                    value = obj.CacheMap{i, 2};
                    return
                end
            end
            value = [];
        end
        
        function len = getCacheLength(obj)
            len = size(obj.CacheMap, 1);
        end
        
        function clear(obj)
            % Manually clear the cluster objects from the cache
            [obj.CacheMap{:}]  = deal([]);
        end
        
    end
end
