defu.cjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function isPlainObject(value) {
  4. if (value === null || typeof value !== "object") {
  5. return false;
  6. }
  7. const prototype = Object.getPrototypeOf(value);
  8. if (prototype !== null && prototype !== Object.prototype && Object.getPrototypeOf(prototype) !== null) {
  9. return false;
  10. }
  11. if (Symbol.iterator in value) {
  12. return false;
  13. }
  14. if (Symbol.toStringTag in value) {
  15. return Object.prototype.toString.call(value) === "[object Module]";
  16. }
  17. return true;
  18. }
  19. function _defu(baseObject, defaults, namespace = ".", merger) {
  20. if (!isPlainObject(defaults)) {
  21. return _defu(baseObject, {}, namespace, merger);
  22. }
  23. const object = Object.assign({}, defaults);
  24. for (const key in baseObject) {
  25. if (key === "__proto__" || key === "constructor") {
  26. continue;
  27. }
  28. const value = baseObject[key];
  29. if (value === null || value === void 0) {
  30. continue;
  31. }
  32. if (merger && merger(object, key, value, namespace)) {
  33. continue;
  34. }
  35. if (Array.isArray(value) && Array.isArray(object[key])) {
  36. object[key] = [...value, ...object[key]];
  37. } else if (isPlainObject(value) && isPlainObject(object[key])) {
  38. object[key] = _defu(
  39. value,
  40. object[key],
  41. (namespace ? `${namespace}.` : "") + key.toString(),
  42. merger
  43. );
  44. } else {
  45. object[key] = value;
  46. }
  47. }
  48. return object;
  49. }
  50. function createDefu(merger) {
  51. return (...arguments_) => (
  52. // eslint-disable-next-line unicorn/no-array-reduce
  53. arguments_.reduce((p, c) => _defu(p, c, "", merger), {})
  54. );
  55. }
  56. const defu = createDefu();
  57. const defuFn = createDefu((object, key, currentValue) => {
  58. if (object[key] !== void 0 && typeof currentValue === "function") {
  59. object[key] = currentValue(object[key]);
  60. return true;
  61. }
  62. });
  63. const defuArrayFn = createDefu((object, key, currentValue) => {
  64. if (Array.isArray(object[key]) && typeof currentValue === "function") {
  65. object[key] = currentValue(object[key]);
  66. return true;
  67. }
  68. });
  69. exports.createDefu = createDefu;
  70. exports.default = defu;
  71. exports.defu = defu;
  72. exports.defuArrayFn = defuArrayFn;
  73. exports.defuFn = defuFn;