DiffCodec.js 1010 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /* eslint-disable
  2. camelcase,
  3. handle-callback-err,
  4. new-cap,
  5. no-throw-literal,
  6. no-unused-vars,
  7. */
  8. let DiffCodec
  9. const { diff_match_patch } = require('../lib/diff_match_patch')
  10. const dmp = new diff_match_patch()
  11. module.exports = DiffCodec = {
  12. ADDED: 1,
  13. REMOVED: -1,
  14. UNCHANGED: 0,
  15. diffAsShareJsOp(before, after, callback) {
  16. const diffs = dmp.diff_main(before.join('\n'), after.join('\n'))
  17. dmp.diff_cleanupSemantic(diffs)
  18. const ops = []
  19. let position = 0
  20. for (const diff of diffs) {
  21. const type = diff[0]
  22. const content = diff[1]
  23. if (type === this.ADDED) {
  24. ops.push({
  25. i: content,
  26. p: position
  27. })
  28. position += content.length
  29. } else if (type === this.REMOVED) {
  30. ops.push({
  31. d: content,
  32. p: position
  33. })
  34. } else if (type === this.UNCHANGED) {
  35. position += content.length
  36. } else {
  37. throw 'Unknown type'
  38. }
  39. }
  40. callback(null, ops)
  41. }
  42. }