DiffCodec.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* eslint-disable
  2. camelcase,
  3. handle-callback-err,
  4. new-cap,
  5. no-throw-literal,
  6. no-unused-vars,
  7. */
  8. // TODO: This file was created by bulk-decaffeinate.
  9. // Fix any style issues and re-enable lint.
  10. /*
  11. * decaffeinate suggestions:
  12. * DS101: Remove unnecessary use of Array.from
  13. * DS102: Remove unnecessary code created because of implicit returns
  14. * DS207: Consider shorter variations of null checks
  15. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  16. */
  17. let DiffCodec;
  18. const {
  19. diff_match_patch
  20. } = require("../lib/diff_match_patch");
  21. const dmp = new diff_match_patch();
  22. module.exports = (DiffCodec = {
  23. ADDED: 1,
  24. REMOVED: -1,
  25. UNCHANGED: 0,
  26. diffAsShareJsOp(before, after, callback) {
  27. if (callback == null) { callback = function(error, ops) {}; }
  28. const diffs = dmp.diff_main(before.join("\n"), after.join("\n"));
  29. dmp.diff_cleanupSemantic(diffs);
  30. const ops = [];
  31. let position = 0;
  32. for (const diff of Array.from(diffs)) {
  33. const type = diff[0];
  34. const content = diff[1];
  35. if (type === this.ADDED) {
  36. ops.push({
  37. i: content,
  38. p: position
  39. });
  40. position += content.length;
  41. } else if (type === this.REMOVED) {
  42. ops.push({
  43. d: content,
  44. p: position
  45. });
  46. } else if (type === this.UNCHANGED) {
  47. position += content.length;
  48. } else {
  49. throw "Unknown type";
  50. }
  51. }
  52. return callback(null, ops);
  53. }
  54. });