udiff.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. var DiffMatchPatch = require('diff-match-patch');
  3. var dmp = new DiffMatchPatch();
  4. function udiff (config) {
  5. return function diff (text1, text2) {
  6. var patch;
  7. if (config && shouldUseLineLevelDiff(text1, config)) {
  8. patch = udiffLines(text1, text2);
  9. } else {
  10. patch = udiffChars(text1, text2);
  11. }
  12. return decodeURIComponent(patch);
  13. };
  14. }
  15. function shouldUseLineLevelDiff (text, config) {
  16. return config.lineDiffThreshold < text.split(/\r\n|\r|\n/).length;
  17. }
  18. function udiffLines(text1, text2) {
  19. /*jshint camelcase: false */
  20. var a = dmp.diff_linesToChars_(text1, text2);
  21. var diffs = dmp.diff_main(a.chars1, a.chars2, false);
  22. dmp.diff_charsToLines_(diffs, a.lineArray);
  23. dmp.diff_cleanupSemantic(diffs);
  24. return dmp.patch_toText(dmp.patch_make(text1, diffs));
  25. }
  26. function udiffChars (text1, text2) {
  27. /*jshint camelcase: false */
  28. var diffs = dmp.diff_main(text1, text2, false);
  29. dmp.diff_cleanupSemantic(diffs);
  30. return dmp.patch_toText(dmp.patch_make(text1, diffs));
  31. }
  32. module.exports = udiff;