Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

cachedMerge.js 1.1KB

1234567891011121314151617181920212223242526272829303132333435
  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 Object.assign(first, second), stores the result in WeakMap and returns result
  11. * cachedMerge({a: 1}, {a: 2})
  12. * {a: 2}
  13. * // when same arguments passed, gets the result from WeakMap and returns it.
  14. * cachedMerge({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 cachedMerge = (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 = Object.assign({}, first, second);
  29. innerCache.set(second, newMerge);
  30. return newMerge;
  31. };
  32. module.exports = cachedMerge;