Skip to content

Instantly share code, notes, and snippets.

@Williammer
Created June 10, 2014 04:32
Show Gist options
  • Select an option

  • Save Williammer/4e933fd5ab91be596a4b to your computer and use it in GitHub Desktop.

Select an option

Save Williammer/4e933fd5ab91be596a4b to your computer and use it in GitHub Desktop.
javaScript.closureCacheFn.js - to cache fns with closure, privacy of cache and nextId improved.
var store = (function () {
var nextId = 1,
cache = {};
return {
addFn: function (fn) {
if (!fn.id) {
fn.id = nextId;
nextId += 1;
return !!(cache[fn.id] = fn);
} else {
return false;
}
},
getCache: function (id) {
return cache[id] ? cache[id] : cache;
},
getLength: function () {
return nextId - 1;
}
};
})();
//test
var testFn = function (aa) {
console.log('test only');
};
console.log(store.addFn(testFn));
console.log(store.addFn(function (aa) {
console.log('test only');
}));
console.log(store.getCache());
console.log(store.getLength());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment