Skip to content

Instantly share code, notes, and snippets.

@shash7
Created August 25, 2014 10:36
Show Gist options
  • Save shash7/1589ad22b9a84d0af853 to your computer and use it in GitHub Desktop.
Save shash7/1589ad22b9a84d0af853 to your computer and use it in GitHub Desktop.
A simple cache for storing objects in javascript
/* jslint undef: true, vars: true */
/* global window, document, $ */
/*
* cache.js
*
* Used for caching objects in an array
*/
(function(window, document, undefined) {
'use strict';
function cache() {
var arr = [];
function compact(arr) {
arr = arr.map(function(data) {
if(data) {
return data;
}
});
return arr;
}
function set(key, value) {
arr.push({
key : key,
value : value
});
return true;
}
function get(key) {
var result;
arr.map(function(data) {
if(data.key === key) {
result = data.value;
}
});
return result;
}
function remove(key) {
arr = arr.map(function(data) {
if(data.key === key) {
data = null;
}
return data;
});
arr = compact(arr);
return true;
}
function getAll() {
return arr;
}
return {
set : set,
get : get,
remove : remove,
getAll : getAll
};
}
window.Cache = cache;
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment