Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active December 15, 2017 14:11
Show Gist options
  • Save ccnokes/4826112ae744fb9b9e4895c99c0a63d8 to your computer and use it in GitHub Desktop.
Save ccnokes/4826112ae744fb9b9e4895c99c0a63d8 to your computer and use it in GitHub Desktop.
A map that lazily gets and caches values on access
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