﻿//-----------------------------------------------------------------------------
// XCache
//
// Copyright 2005-2010 - Xcential Group LLC.
//
//-----------------------------------------------------------------------------

XCache.prototype = new XObject;
XCache.prototype.constructor = XCache;

//=============================================================================
// Constructor

function XCache(
   maxLength,
   create
)
{
   maxLength = (maxLength == null) ? 20 : maxLength;
   create = (create == null) ? true : create;

   if (create)
      return new XCache(maxLength, false);

   //--------------------------------------------------------------------------
   // Private Interface

   //--------------------------------------------------------------------------
   // Privileged Interface

   this.valueOf = function()
   {

      return oCache;
   }

   //--------------------------------------------------------------------------
   // Initialization

   var oCache = new Array();
   oCache.maxLength = maxLength;

}

XCache.prototype.objectClass = "XCache";

//=============================================================================
// Static Interface


//=============================================================================
// Public Interface

XCache.prototype.getItem = function(
   identifier,
   castAs
)
{
   castAs = (castAs == null) ? null : castAs;

   var cache = this.valueOf();

   var itemInfo = cache[identifier];

   if (!itemInfo)
      return null;

   try
   {
      itemInfo.count++;
      return (castAs == null) ? itemInfo.data : castAs(itemInfo.data);
   }
   catch (error)
   {
      return null;
   }
}

//-----------------------------------------------------------------------------

XCache.prototype.addItem = function(
   identifier,
   item
)
{
   item = (item == null) ? null : item;

   var cache = this.valueOf();

   var itemInfo = new Array();
   itemInfo.identifier = identifier;
   itemInfo.count = 1;
   itemInfo.data = item;
   cache.push(itemInfo);
   cache[identifier] = itemInfo;

   // Choose what to take out if we are at the limit
   if (cache.length > cache.maxLength)
   {
      var victim = null;
      for (var i=0; i<cache.length; i++)
      {
         var itemInfo = cache[i];
         itemInfo.index = i;
         itemInfo.points = itemInfo.index + itemInfo.count;
         victim = (!victim || itemInfo.points < victim.points) ? itemInfo : victim;
      }

      cache[victim.identifier] = null;
      cache.splice(victim.index, 1);
   }

}

//=============================================================================
