lazy-helpers.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export class DelayedConstructor {
  2. constructor(wrap) {
  3. this.wrap = wrap;
  4. this.reflectMethods = [
  5. "get",
  6. "getPrototypeOf",
  7. "setPrototypeOf",
  8. "getOwnPropertyDescriptor",
  9. "defineProperty",
  10. "has",
  11. "set",
  12. "deleteProperty",
  13. "apply",
  14. "construct",
  15. "ownKeys"
  16. ];
  17. }
  18. createProxy(createObject) {
  19. const target = {};
  20. let init = false;
  21. let value;
  22. const delayedObject = () => {
  23. if (!init) {
  24. value = createObject(this.wrap());
  25. init = true;
  26. }
  27. return value;
  28. };
  29. return new Proxy(target, this.createHandler(delayedObject));
  30. }
  31. createHandler(delayedObject) {
  32. const handler = {};
  33. const install = (name) => {
  34. handler[name] = (...args) => {
  35. args[0] = delayedObject();
  36. const method = Reflect[name];
  37. return method(...args);
  38. };
  39. };
  40. this.reflectMethods.forEach(install);
  41. return handler;
  42. }
  43. }
  44. export function delay(wrappedConstructor) {
  45. if (typeof wrappedConstructor === "undefined") {
  46. throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");
  47. }
  48. return new DelayedConstructor(wrappedConstructor);
  49. }