index.cjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. const isWhat = require('is-what');
  3. function assignProp(carry, key, newVal, originalObject, includeNonenumerable) {
  4. const propType = {}.propertyIsEnumerable.call(originalObject, key) ? "enumerable" : "nonenumerable";
  5. if (propType === "enumerable")
  6. carry[key] = newVal;
  7. if (includeNonenumerable && propType === "nonenumerable") {
  8. Object.defineProperty(carry, key, {
  9. value: newVal,
  10. enumerable: false,
  11. writable: true,
  12. configurable: true
  13. });
  14. }
  15. }
  16. function copy(target, options = {}) {
  17. if (isWhat.isArray(target)) {
  18. return target.map((item) => copy(item, options));
  19. }
  20. if (!isWhat.isPlainObject(target)) {
  21. return target;
  22. }
  23. const props = Object.getOwnPropertyNames(target);
  24. const symbols = Object.getOwnPropertySymbols(target);
  25. return [...props, ...symbols].reduce((carry, key) => {
  26. if (isWhat.isArray(options.props) && !options.props.includes(key)) {
  27. return carry;
  28. }
  29. const val = target[key];
  30. const newVal = copy(val, options);
  31. assignProp(carry, key, newVal, target, options.nonenumerable);
  32. return carry;
  33. }, {});
  34. }
  35. exports.copy = copy;