Javascript Data Cache

I was looking for a way to cache data in JavaScript so i wrote this little ditty.

I need to spend a little time optimising it but here is the code in its initial form.

This works as part of my mean.js service class stack.

‘use strict’;

/**
* Module dependencies.
*/
var cacheStore = [];
/**
* Update user details
*/
exports.add = function(key,value,cacheTimeinSeconds) {
// Init Variables
var cachedate = new Date().getTime();

key = key.toUpperCase();

if (!cacheTimeinSeconds)
{
// default 60 seconds
cachedate = cachedate + (60 * 1000);
}
else
{
cachedate = cachedate + (cacheTimeinSeconds * 1000);
}
var dataitem = {};
dataitem.key = key;
dataitem.value = value;
dataitem.expiry = cachedate;
dataitem.hasExpired = false;
var emptySlotFound = false;
for (var i = 0; i < cacheStore.length; i++)
{
if (cacheStore[i].hasExpired)
{
cacheStore[i] = dataitem;
emptySlotFound = true;
break;
}
}

if (!emptySlotFound)
{
cacheStore.push(dataitem);
}
console.log(‘>>>>>>>> Cache item added : ‘ + key + ‘ <<<<<<<<<<‘);

};

exports.get = function(key) {

key = key.toUpperCase();

var currentdate = new Date().getTime();
// Init Variables
for (var i = 0; i < cacheStore.length; i++)
{
if (cacheStore[i].expiry < currentdate)
{
cacheStore[i].key = ”;
cacheStore[i].value = null;
cacheStore[i].hasExpired = true;
}
}

for (i = 0; i < cacheStore.length; i++)
{
if (cacheStore[i].key === key && !cacheStore[i].hasExpired)
{
console.log(‘ Cache item retrieved : ‘ + key + ‘ <<<<<<<<<<‘);
return cacheStore[i].value;
}

}

return undefined;
};
exports.RemoveAllExpiredItems = function() {
var arrayOfExpiredIndexes = [];

for (var i = 0; i < cacheStore.length; i++)
{
if (cacheStore[i].hasExpired === true)
{
arrayOfExpiredIndexes.push(i);
}
}

for (i = 0; i < arrayOfExpiredIndexes.length; i++)
{
cacheStore.splice(arrayOfExpiredIndexes[i],1);
}
};

exports.ClearAllCache = function() {

cacheStore = [];

};

Advertisements
Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: