defu.mjs 2.0 KB

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