diff.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import _typeof from "@babel/runtime/helpers/esm/typeof";
  2. import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
  3. import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
  4. /* eslint no-proto: 0 */
  5. function createArray() {
  6. var arr = [];
  7. arr.__proto__ = new Array();
  8. arr.__proto__.format = function toString() {
  9. return this.map(function (obj) {
  10. return _objectSpread(_objectSpread({}, obj), {}, {
  11. path: obj.path.join(' > ')
  12. });
  13. });
  14. };
  15. arr.__proto__.toString = function toString() {
  16. return JSON.stringify(this.format(), null, 2);
  17. };
  18. return arr;
  19. }
  20. export default function diff(obj1, obj2) {
  21. var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10;
  22. var path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  23. var diffList = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : createArray();
  24. if (depth <= 0) return diffList;
  25. var keys = new Set([].concat(_toConsumableArray(Object.keys(obj1)), _toConsumableArray(Object.keys(obj2))));
  26. keys.forEach(function (key) {
  27. var value1 = obj1[key];
  28. var value2 = obj2[key];
  29. // Same value
  30. if (value1 === value2) return;
  31. var type1 = _typeof(value1);
  32. var type2 = _typeof(value2);
  33. // Diff type
  34. if (type1 !== type2) {
  35. diffList.push({
  36. path: path.concat(key),
  37. value1: value1,
  38. value2: value2
  39. });
  40. return;
  41. }
  42. // NaN
  43. if (Number.isNaN(value1) && Number.isNaN(value2)) {
  44. return;
  45. }
  46. // Object & Array
  47. if (type1 === 'object' && value1 !== null && value2 !== null) {
  48. diff(value1, value2, depth - 1, path.concat(key), diffList);
  49. return;
  50. }
  51. // Rest
  52. diffList.push({
  53. path: path.concat(key),
  54. value1: value1,
  55. value2: value2
  56. });
  57. });
  58. return diffList;
  59. }