DiffCodec.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS207: Consider shorter variations of null checks
  14. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  15. */
  16. let DiffCodec
  17. const { diff_match_patch } = require('../lib/diff_match_patch')
  18. const dmp = new diff_match_patch()
  19. module.exports = DiffCodec = {
  20. ADDED: 1,
  21. REMOVED: -1,
  22. UNCHANGED: 0,
  23. diffAsShareJsOp(before, after, callback) {
  24. if (callback == null) {
  25. callback = function (error, ops) {}
  26. }
  27. const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
  28. dmp.diff_cleanupSemantic(diffs)
  29. const ops = []
  30. let position = 0
  31. for (const diff of diffs) {
  32. const type = diff[0]
  33. const content = diff[1]
  34. if (type === this.ADDED) {
  35. ops.push({
  36. i: content,
  37. p: position
  38. })
  39. position += content.length
  40. } else if (type === this.REMOVED) {
  41. ops.push({
  42. d: content,
  43. p: position
  44. })
  45. } else if (type === this.UNCHANGED) {
  46. position += content.length
  47. } else {
  48. throw 'Unknown type'
  49. }
  50. }
  51. return callback(null, ops)
  52. }
  53. }