DiffCodec.js 964 B

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