index.cjs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var isWhat = require('is-what');
  4. function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  5. const propType = {}.propertyIsEnumerable.call(originalObject, key)
  6. ? 'enumerable'
  7. : 'nonenumerable';
  8. if (propType === 'enumerable')
  9. carry[key] = newVal;
  10. if (includeNonenumerable && propType === 'nonenumerable') {
  11. Object.defineProperty(carry, key, {
  12. value: newVal,
  13. enumerable: false,
  14. writable: true,
  15. configurable: true,
  16. });
  17. }
  18. }
  19. /**
  20. * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the original object. Arrays are also cloned, however objects inside arrays are still linked.
  21. *
  22. * @export
  23. * @template T
  24. * @param {T} target Target can be anything
  25. * @param {Options} [options = {}] Options can be `props` or `nonenumerable`
  26. * @returns {T} the target with replaced values
  27. * @export
  28. */
  29. function copy(target, options = {}) {
  30. if (isWhat.isArray(target)) {
  31. return target.map((item) => copy(item, options));
  32. }
  33. if (!isWhat.isPlainObject(target)) {
  34. return target;
  35. }
  36. const props = Object.getOwnPropertyNames(target);
  37. const symbols = Object.getOwnPropertySymbols(target);
  38. return [...props, ...symbols].reduce((carry, key) => {
  39. if (isWhat.isArray(options.props) && !options.props.includes(key)) {
  40. return carry;
  41. }
  42. const val = target[key];
  43. const newVal = copy(val, options);
  44. assignProp(carry, key, newVal, target, options.nonenumerable);
  45. return carry;
  46. }, {});
  47. }
  48. exports.copy = copy;