You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.1 KiB

4 years ago
  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;