- 1 :
/**
- 2 :
* Object.defineProperty but "lazy", which means that the value is only set after
- 3 :
* it retrieved the first time, rather than being set right away.
- 4 :
*
- 5 :
* @param {Object} obj the object to set the property on
- 6 :
* @param {string} key the key for the property to set
- 7 :
* @param {Function} getValue the function used to get the value when it is needed.
- 8 :
* @param {boolean} setter wether a setter shoould be allowed or not
- 9 :
*/
- 10 :
const defineLazyProperty = function(obj, key, getValue, setter = true) {
- 11 :
const set = (value) =>
- 12 :
Object.defineProperty(obj, key, {value, enumerable: true, writable: true});
- 13 :
- 14 :
const options = {
- 15 :
configurable: true,
- 16 :
enumerable: true,
- 17 :
get() {
- 18 :
const value = getValue();
- 19 :
- 20 :
set(value);
- 21 :
- 22 :
return value;
- 23 :
}
- 24 :
};
- 25 :
- 26 :
if (setter) {
- 27 :
options.set = set;
- 28 :
}
- 29 :
- 30 :
return Object.defineProperty(obj, key, options);
- 31 :
};
- 32 :
- 33 :
export default defineLazyProperty;