Skip to content

Instantly share code, notes, and snippets.

@aurri
Last active August 29, 2015 14:03
Show Gist options
  • Save aurri/10e4002e425d9cc8351e to your computer and use it in GitHub Desktop.
Save aurri/10e4002e425d9cc8351e to your computer and use it in GitHub Desktop.
Lazy object properties
/////////////////////////////////////////////////
//// Lazy object properties
/////////////////////////////////////////////////
// Sets a property that computes its value on first access
// (see a test below for usage example)
function lazy(obj, prop, fn){
if(typeof prop === 'string') set(prop, fn)
else Object.keys(prop).forEach(function(k){ set(k, prop[k]) })
function set(name, fn){
// Set getter
Object.defineProperty(obj, name, {
get: function(){
// Calculate value on first access
var value = fn(name, obj)
// Set value
Object.defineProperty(obj, name, {
value: value,
enumerable: true,
configurable: true,
writable: true
})
return value
},
enumerable: true,
configurable: true
})
}
return obj
}
/*
(function test(){
var obj = lazy({}, {test: function(){ return Math.random() }})
// Test
var calculated = obj.test
var predefined = obj.test
console.log(calculated === predefined, calculated, predefined)
})()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment