Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

cleverMerge.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const mergeCache = new WeakMap();
  7. /**
  8. * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again.
  9. * @example
  10. * // performs cleverMerge(first, second), stores the result in WeakMap and returns result
  11. * cachedCleverMerge({a: 1}, {a: 2})
  12. * {a: 2}
  13. * // when same arguments passed, gets the result from WeakMap and returns it.
  14. * cachedCleverMerge({a: 1}, {a: 2})
  15. * {a: 2}
  16. * @param {object} first first object
  17. * @param {object} second second object
  18. * @returns {object} merged object of first and second object
  19. */
  20. const cachedCleverMerge = (first, second) => {
  21. let innerCache = mergeCache.get(first);
  22. if (innerCache === undefined) {
  23. innerCache = new WeakMap();
  24. mergeCache.set(first, innerCache);
  25. }
  26. const prevMerge = innerCache.get(second);
  27. if (prevMerge !== undefined) return prevMerge;
  28. const newMerge = cleverMerge(first, second);
  29. innerCache.set(second, newMerge);
  30. return newMerge;
  31. };
  32. /**
  33. * Merges two objects. Objects are not deeply merged.
  34. * TODO webpack 5: merge objects deeply clever.
  35. * Arrays might reference the old value with "..."
  36. * @param {object} first first object
  37. * @param {object} second second object
  38. * @returns {object} merged object of first and second object
  39. */
  40. const cleverMerge = (first, second) => {
  41. const newObject = Object.assign({}, first);
  42. for (const key of Object.keys(second)) {
  43. if (!(key in newObject)) {
  44. newObject[key] = second[key];
  45. continue;
  46. }
  47. const secondValue = second[key];
  48. if (!Array.isArray(secondValue)) {
  49. newObject[key] = secondValue;
  50. continue;
  51. }
  52. const firstValue = newObject[key];
  53. if (Array.isArray(firstValue)) {
  54. const newArray = [];
  55. for (const item of secondValue) {
  56. if (item === "...") {
  57. for (const item of firstValue) {
  58. newArray.push(item);
  59. }
  60. } else {
  61. newArray.push(item);
  62. }
  63. }
  64. newObject[key] = newArray;
  65. } else {
  66. newObject[key] = secondValue;
  67. }
  68. }
  69. return newObject;
  70. };
  71. exports.cachedCleverMerge = cachedCleverMerge;
  72. exports.cleverMerge = cleverMerge;