src/lens_factory.js

  1. import BinderMixin from './binder_mixin.js';
  2. import CCCLens from './ccc_lens.js';
  3. import { DEFAULT_FACTORY as jsContainers } from './js_container_factory.js';
  4. /**
  5. * @interface ContainerFactory
  6. * @see Factory
  7. */
  8. /**
  9. * @function ContainerFactory#construct
  10. * @summary Construct a missing container
  11. * @param {Array} keys The keys up to and including the one indexing into the missing container
  12. * @returns {*} The missing container
  13. */
  14. class LensFactory {
  15. /**
  16. * @constructs Factory
  17. * @summary A factory for Lens-derived objects with customized container construction
  18. * @mixes BinderMixin
  19. * @param {Object} spec
  20. * @param {ContainerFactory} spec.containerFactory Factory for containers, used by [Lenses]{@link Lens} created by this Factory, invoked when modify-cloning missing containers in subject data
  21. *
  22. * @description
  23. * When POD container types (Object and Array) are not the desired types to
  24. * construct in a clone -- as with use of immutable containers -- this class
  25. * can be used to build lenses that *do* build the desired types of objects.
  26. *
  27. * This class is often used in conjunction with a JsContainerFactory object
  28. * implementing the container factory.
  29. */
  30. constructor({containerFactory = jsContainers} = {}) {
  31. this.containerFactory = containerFactory;
  32. }
  33. /**
  34. * @function Factory#lens
  35. * @summary Construct a lens through the factory
  36. * @param {...*} key A key of the customized lens type
  37. * @returns {Lens} A lens with customized container creation behavior
  38. * @see module:natural-lenses
  39. *
  40. * @description
  41. * This method works the same way as the main {@link Lens} constructor of
  42. * {@link module:natural-lenses}, except that missing container construction
  43. * is managed via the {@link ContainerFactory} with which this Factory was
  44. * constructed.
  45. */
  46. lens(...keys) {
  47. const result = new CCCLens(...keys);
  48. result._containerFactory = this.containerFactory;
  49. return result;
  50. }
  51. }
  52. Object.assign(LensFactory.prototype, BinderMixin);
  53. export default LensFactory;