Created
June 10, 2014 04:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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