Guest User

Untitled

a guest
Nov 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. function diff(source, target) {
  2. source = JSON.parse(JSON.stringify(source)).map(JSON.stringify);
  3. target = JSON.parse(JSON.stringify(target)).map(JSON.stringify);
  4.  
  5. var changes = [];
  6.  
  7. while (source.length && target.length) {
  8. var oldVal = source.shift();
  9. var newVal = target.shift();
  10.  
  11. var added = target.indexOf(oldVal);
  12. var removed = source.indexOf(newVal);
  13.  
  14. if (JSON.stringify(oldVal) == JSON.stringify(newVal)) {
  15. // If the values are the same, there was no change.
  16. changes.push({ action: 'keep', value: JSON.parse(newVal) });
  17.  
  18. } else if (~added || ~removed) {
  19. // If the current value appears later in either array, we've something
  20. // has been changed between here and there.
  21. var inserting = ! ~removed || (~added && source.length < target.length);
  22.  
  23. var row = inserting ? target : source;
  24. var action = inserting ? 'insert' : 'delete';
  25. var value = inserting ? newVal : oldVal;
  26.  
  27. row.unshift(value);
  28. for (var i = 0; i <= (inserting ? added : removed); i++) {
  29. changes.push({ action: action, value: JSON.parse(row.shift()) });
  30. }
  31. changes.push({ action: 'keep', value: JSON.parse(row.shift()) });
  32. } else {
  33. // Otherwise, we should replace the old value with the new one.
  34. changes.push({ action: 'change', value: JSON.parse(newVal), previous: JSON.parse(oldVal) });
  35. }
  36. }
  37.  
  38. // Add changes for anything remaining at the end of the list.
  39. source.forEach(function(val) {
  40. changes.push({ action: 'delete', value: JSON.parse(val) });
  41. });
  42.  
  43. target.forEach(function(val) {
  44. changes.push({ action: 'insert', value: JSON.parse(val) });
  45. });
  46.  
  47. return changes;
  48. }
Add Comment
Please, Sign In to add comment