Last active
December 15, 2017 14:11
-
-
Save ccnokes/4826112ae744fb9b9e4895c99c0a63d8 to your computer and use it in GitHub Desktop.
A map that lazily gets and caches values on access
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
function makeLazy(name, fn, obj = {}) { | |
const nullSym = Symbol('nil'); //could change this to be more es5 friendly | |
let val = nullSym; //I'm not sure if holding the value in this closure or right on the object is better | |
Object.defineProperty(obj, name, { | |
enumerable: true, | |
get() { | |
if(val === nullSym) { | |
val = fn(); | |
} | |
return val; | |
}, | |
set(newVal) { | |
val = newVal; | |
} | |
}); | |
return obj; | |
} | |
function makeLazyContainer(map, targetObj = {}) { | |
for(let name in map) { | |
makeLazy(name, map[name], targetObj); | |
} | |
return targetObj; | |
} | |
/* Implement it... */ | |
//DOM query isn't made until needed, and then it's cached | |
const lazyDomEls = makeLazyContainer({ | |
body: () => document.querySelector('body'), | |
divs: () => document.querySelectorAll('div') | |
}); | |
// Usage: | |
lazyDomEls.body; //the query is made on first access | |
lazyDomEls.body; //subsequent accesses just return the cached value | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment