Last active
August 29, 2015 14:03
-
-
Save aurri/10e4002e425d9cc8351e to your computer and use it in GitHub Desktop.
Lazy object properties
This file contains 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
///////////////////////////////////////////////// | |
//// 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