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