DiffCodec.js 953 B

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