src/immutable_support.js

  1. import { forEach } from 'underscore';
  2. import { at_maybe, cloneImpl } from '../src-cjs/constants.js';
  3. function ImmutableMixin({spliceOutWithDelete}) {
  4. return {
  5. [at_maybe]: function (key) {
  6. return this.has(key) ? {just: this.get(key)} : {};
  7. },
  8. [cloneImpl]: function ({pop, set, spliceOut}) {
  9. /* istanbul ignore next: unsupported */
  10. if (pop) {
  11. return this.pop();
  12. }
  13. if (set) {
  14. return this.set(...set);
  15. }
  16. if (spliceOut) {
  17. return spliceOutWithDelete ? this.delete(spliceOut) : this.set(spliceOut, undefined);
  18. }
  19. /* istanbul ignore next: no change requested */
  20. return this;
  21. },
  22. };
  23. }
  24. /**
  25. * @function module:natural-lenses#polyfillImmutable
  26. * @summary Add lensing support methods to an Immutable type
  27. * @param {Function} containerType Target container type for support
  28. *
  29. * @description
  30. * Adds mixin methods for supporting lenses to the given Immutable container
  31. * type.
  32. */
  33. function polyfillImmutable(containerType) {
  34. const isList = containerType.isList;
  35. const proto = containerType.prototype,
  36. mixins = ImmutableMixin({spliceOutWithDelete: !isList});
  37. forEach(
  38. Object.getOwnPropertySymbols(mixins),
  39. (name) => {
  40. if (!proto.hasOwnProperty(name)) {
  41. Object.defineProperty(proto, name, {
  42. enumerable: false,
  43. configurable: true,
  44. writable: true,
  45. value: mixins[name],
  46. });
  47. }
  48. }
  49. )
  50. }
  51. export { polyfillImmutable };