defu.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. function isObject(val) {
  3. return val !== null && typeof val === "object";
  4. }
  5. function _defu(baseObj, defaults, namespace = ".", merger) {
  6. if (!isObject(defaults)) {
  7. return _defu(baseObj, {}, namespace, merger);
  8. }
  9. const obj = Object.assign({}, defaults);
  10. for (const key in baseObj) {
  11. if (key === "__proto__" || key === "constructor") {
  12. continue;
  13. }
  14. const val = baseObj[key];
  15. if (val === null) {
  16. continue;
  17. }
  18. if (merger && merger(obj, key, val, namespace)) {
  19. continue;
  20. }
  21. if (Array.isArray(val) && Array.isArray(obj[key])) {
  22. obj[key] = obj[key].concat(val);
  23. } else if (isObject(val) && isObject(obj[key])) {
  24. obj[key] = _defu(val, obj[key], (namespace ? `${namespace}.` : "") + key.toString(), merger);
  25. } else {
  26. obj[key] = val;
  27. }
  28. }
  29. return obj;
  30. }
  31. function extend(merger) {
  32. return (...args) => args.reduce((p, c) => _defu(p, c, "", merger), {});
  33. }
  34. const defu = extend();
  35. defu.fn = extend((obj, key, currentValue, _namespace) => {
  36. if (typeof obj[key] !== "undefined" && typeof currentValue === "function") {
  37. obj[key] = currentValue(obj[key]);
  38. return true;
  39. }
  40. });
  41. defu.arrayFn = extend((obj, key, currentValue, _namespace) => {
  42. if (Array.isArray(obj[key]) && typeof currentValue === "function") {
  43. obj[key] = currentValue(obj[key]);
  44. return true;
  45. }
  46. });
  47. defu.extend = extend;
  48. module.exports = defu;