utils.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * This file is part of OsmInEdit, released under ISC license (see LICENSE.md)
  3. *
  4. * Copyright (c) Adrien Pavie 2019
  5. * Copyright (c) Daimler AG 2019
  6. *
  7. * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  10. *
  11. */
  12. import deepEqual from 'fast-deep-equal';
  13. /**
  14. * Simple object check.
  15. * @private
  16. */
  17. const _isObject = (item) => {
  18. return (item && typeof item === 'object' && !Array.isArray(item));
  19. };
  20. /**
  21. * Deep merge two objects.
  22. */
  23. const mergeDeep = (target, ...sources) => {
  24. if (!sources.length) return target;
  25. const source = sources.shift();
  26. if (_isObject(target) && _isObject(source)) {
  27. for (const key in source) {
  28. if (_isObject(source[key])) {
  29. if (!target[key]) Object.assign(target, { [key]: {} });
  30. mergeDeep(target[key], source[key]);
  31. }
  32. else if(Array.isArray(source[key]) && Array.isArray(target[key])) {
  33. target[key] = target[key].concat(source[key]);
  34. }
  35. else {
  36. Object.assign(target, { [key]: source[key] });
  37. }
  38. }
  39. }
  40. return mergeDeep(target, ...sources);
  41. };
  42. /**
  43. * Return array of coordinates with a precision of 8 digits (OSM)
  44. */
  45. const fixPrecision = coords => coords.map(c => {
  46. if(typeof c === "string") { c = parseFloat(c); }
  47. return parseFloat(c.toFixed(8));
  48. });
  49. /**
  50. * List of common elements between two arrays (intersection)
  51. */
  52. const intersectionArray = function(arrA, arrB) {
  53. const common = [];
  54. const minimal = arrA.length < arrB.length ? arrA : arrB;
  55. const other = arrA.length < arrB.length ? arrB : arrA;
  56. minimal.forEach(el => {
  57. if(other.find(el2 => deepEqual(el, el2)) && !common.find(el2 => deepEqual(el, el2))) {
  58. common.push(el);
  59. }
  60. });
  61. return common;
  62. }
  63. export { mergeDeep, fixPrecision, intersectionArray };